简体   繁体   English

将列名作为参数传递给函数

[英]Pass column names as argument into a function

I created a data table df我创建了一个数据表df

library(data.table)
df <- data.table(id = c(1,1,1,2,2), starts = c(0,0,6,0,9), ends = c(0,6,10,9,20))

df
   #id starts ends
#1:  1      0    0
#2:  1      0    6
#3:  1      6   10
#4:  2      0    9
#5:  2      9   20

I defined a function 'equal_0', which is entering a col_name , then the function would return a data table with that col_name == 0我定义了一个函数“equal_0”,它输入一个col_name ,然后该函数将返回一个带有col_name == 0的数据表

equal_0 <- function(col_name){
    a <- df[col_name == 0]
    return(a)
}

For example, equal_0(starts) equals to df[starts == 0] , the expected result is:例如, equal_0(starts)等于df[starts == 0] ,预期结果是:

df[starts==0]
   #id starts ends
#1:  1      0    0
#2:  1      0    6
#3:  2      0    9

However, both equal_0(starts) and equal_0("starts") don't work.但是, equal_0(starts)equal_0("starts")都不起作用。

The error message is:错误信息是:

equal_0("starts")
#Empty data.table (0 rows) of 3 cols: id,starts,ends

equal_0(starts)
#Error in eval(.massagei(isub), x, parent.frame()) : object 'starts' not found 

How can I pass starts into the function equal_0 ?如何将starts传递到函数equal_0

Use get to extract column from the data.table:使用get从 data.table 中提取列:

equal_0 <- function(col_name){
    library(data.table)
    a <- df[get(col_name) == 0]
    return(a)
}
equal_0("starts")
   id starts ends
1:  1      0    0
2:  1      0    6
3:  2      0    9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM