Search code examples
rdplyr

arrange data frame on variable name multiplied by a column


I am trying to arrange a data frame by the result of two columns multiplied. The only problem is, that one column name is saved in a variable.

So what I try to achieve is this:

library(dplyr)
data.frame(a=1:10, b=seq(20,1,-2)) %>% arrange(a * b)

But When when I have the a written in a variable:

library(dplyr)
my_var <- 'a'
data.frame(a=1:10, b=seq(20,1,-2)) %>% arrange(!!my_var * b)

I get an error message about non numeric argument.

I also tried quo() which actually suggest to use !! instead.


Solution

  • Use sym()

    data.frame(a=1:10, b=seq(20,1,-2)) %>% arrange(!!sym(my_var) * b)