1

I have a list of formulas which I want to use to create new variables with mutate. For each formula stored in my list, I want to create a new variable. I want to automatically generate one variable for each element in my list. This is my code

library("dplyr")
library("purrr")
library("formula.tools")

t<-10 #just some constant which needs to be included (and found within my pipe)

ut <- list( # my list with the formulas as elements
  v1 = V.1 ~ A * B*t,
  v2 = V.2 ~ A+B)

data <- tibble(A=rnorm(10),B=runif(10)) %>%  ## the dataset
  mutate(!!lhs(ut[["v1"]]) := !!rhs(ut[["v1"]]),
         !!lhs(ut[["v2"]]) := !!rhs(ut[["v2"]]))

This works fine. However, I do not want to write this for each element in my function. I want to mutate to take each element of the list, and apply the formula, i.e. I need some kind of loop. I tried with across, but across requires existing variables.

I tried to wrap it into a function and use map, but this didn't work

by_formula <- function(equation){
 !!lhs(equation) := !!rhs(equation) 
}

data <- tibble(A=rnorm(10),B=runif(10)) %>%
  mutate(map(ut,by_formula))

I appreciate any hints how to do this so that I do not need to worry about the length of the list. This should be part of a function where the length of the list depends on the user input.

1 Answer 1

1

Here is one way

library(dplyr)
library(purrr)
library(formula.tools)
by_formula <- function(equation){
# //! cur_data_all may get deprecated in favor of pick
# pick(everything()) %>%
 cur_data_all() %>%
 transmute(!!lhs(equation) := !!rhs(equation) )
}

 tibble(A=rnorm(10),B=runif(10)) %>% 
    mutate(map_dfc(ut, by_formula))

-output

# A tibble: 10 × 4
        A       B      V.1     V.2
    <dbl>   <dbl>    <dbl>   <dbl>
 1  1.73  0.0770    1.33    1.80  
 2 -1.46  0.894   -13.0    -0.562 
 3 -0.620 0.804    -4.99    0.184 
 4  0.834 0.524     4.37    1.36  
 5 -0.980 0.00581  -0.0569 -0.974 
 6 -0.361 0.316    -1.14   -0.0444
 7  1.73  0.833    14.4     2.57  
 8  1.71  0.512     8.74    2.22  
 9  0.233 0.944     2.20    1.18  
10 -0.832 0.474    -3.94   -0.358 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.