Suppose I have a data frame with column a
and b
:
> library(dplyr)
> df <- data.frame(a=c(1,2,3),b=c(2,3,4))
a b
1 2 2
2 3 3
3 4 4
Now there are two variables which refer to the column names in the data frame:
> col1 <- 'a'
> col2 <- 'b'
I want to use these variables to refer to the columns in dyplyr's mutate
function rather than using the column names directly. The following code works:
> df %>% mutate(a=!!sym(col2))
a b
1 2 2
2 3 3
3 4 4
However if I use unquote before the equal sign, it won't work:
> df %>% mutate(!!sym(var1) = !!sym(var2))
Error: unexpected '=' in "df %>% mutate(!!sym(var1) ="
So how do I make it work in this case? Thanks for any help.