dplyr mutate use standard evaluation

41 views Asked by At

I would like to reference in a dplyr mutate phrase to an object which includes the variable name in my data frame. How can I use standard evaluation in my case:

Here is some dummy data:

data.df<-as.data.frame(cbind(c(1,1,1,1,2,2,2,2,3,3,3,3),c(1,2,3,4,1,2,3,4,1,2,3,4),c(5.5,5.5,3.3,3.3,4.4,4.4,3.3,3.3,5.5,6.6,6.6,5.5)))
colnames(data.df) <- c("id","order_vector","variable")

This is the variable that I want to be able to change:

dependent_variable<-"variable"

It is working for me if the dependent variable is entered directly:

data_lead1.df <- arrange(data.df,id, order_vector) %>% 
    group_by(id) %>%
    mutate(variable_lead = lead(variable, 2))

However, how can I use standard evaluation so that I can reference to the object dependent_variable? I tried the following:

data_lead2.df <- arrange(data.df,id, order_vector) %>% 
    group_by(id) %>%
    mutate_(variable_lead = lead(dependent_variable, 2))

data_lead3.df <- arrange(data.df,id, order_vector) %>% 
    group_by(id) %>%
    mutate_(variable_lead = lead(dependent_variable, 2),.dots=setNames(dependent_variable, "dependent_variable_lead" ))

But both solutions do not provide the same result as the first approach: identical(data_lead1.df$variable_lead,data_lead2.df$variable_lead) false identical(data_lead1.df$variable_lead,data_lead3.df$variable_lead) false

Can someone help, please?

Thank you!!

0

There are 0 answers