R 将列名作为参数传递给函数
我创建了一个数据表R 将列名作为参数传递给函数,r,data.table,R,Data.table,我创建了一个数据表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 例如,equal_0(sta
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
例如,equal_0(start)
等于df[start==0]
,预期结果是:
df[starts==0]
#id starts ends
#1: 1 0 0
#2: 1 0 6
#3: 2 0 9
但是,equal_0(开始)
和equal_0(“开始”)
都不起作用
错误消息是:
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
如何将
start
传递到函数equal_0
?使用get
从数据表中提取列。表:
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
equal_0相关:
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