How to reference columns in a R function?

Asked

Viewed 40 times

3

My question is how to announce a column in the Arglist of a Function.
Example:

I want to do this

library(data.table)    
a<-mtcars
data.table::setDT(a)
a[,.(
     disp2 = sum(disp),
     cyl2 = mean(cyl)
 ), by = .(gear, carb)]

and I want to do this

a<-mtcars
data.table::setDT(a)
a[,.(
     disp2 = sum(disp),
     cyl2 = mean(cyl)
 ), by = .(gear, am)]

So how do I write the function so that it defines the columns of my interest, like this:

a<-mtcars
somaemedia(a, gear, carb)
    gear carb  disp2     cyl2
 1:    4    4  655.2 6.000000
 2:    4    1  336.8 4.000000
 3:    3    1  603.1 5.333333
 4:    3    2 1382.0 8.000000
 5:    3    4 2082.0 8.000000
 6:    4    2  484.2 4.000000
 7:    3    3  827.4 8.000000
 8:    5    2  215.4 4.000000
 9:    5    4  351.0 8.000000
10:    5    6  145.0 6.000000
11:    5    8  301.0 8.000000

and

somaemedia(a, gear, am)
   gear am  disp2     cyl2
1:    4  1  853.5 4.500000
2:    3  0 4894.5 7.466667
3:    4  0  622.7 5.000000
4:    5  1 1012.4 6.000000

1 answer

4


One way to do what the question asks is with deparse/substitute, which transforms the variables passed into function arguments without quotation marks into strings (the variable names), followed by get to obtain the values corresponding to variable names.

somaemedia <- function(DT, col1, col2){
  col1 <- deparse(substitute(col1))
  col2 <- deparse(substitute(col2))
  DT <- DT[,.(
    disp2 = sum(disp),
    cyl2 = mean(cyl)
  ), by = .(get(col1), get(col2))]
  names(DT)[1:2] <- c(col1, col2)
  DT
}

somaemedia(a, gear, am)
#   gear am  disp2     cyl2
#1:    4  1  853.5 4.500000
#2:    3  0 4894.5 7.466667
#3:    4  0  622.7 5.000000
#4:    5  1 1012.4 6.000000

somaemedia(a, gear, carb)
#    gear carb  disp2     cyl2
# 1:    4    4  655.2 6.000000
# 2:    4    1  336.8 4.000000
# 3:    3    1  603.1 5.333333
# 4:    3    2 1382.0 8.000000
# 5:    3    4 2082.0 8.000000
# 6:    4    2  484.2 4.000000
# 7:    3    3  827.4 8.000000
# 8:    5    2  215.4 4.000000
# 9:    5    4  351.0 8.000000
#10:    5    6  145.0 6.000000
#11:    5    8  301.0 8.000000

Browser other questions tagged

You are not signed in. Login or sign up in order to post.