按动态列名过滤数据表 [英] Filter data table by dynamic column name
问题描述
假设我有一个data.table列A,B和C
lets say I have a data.table with columns A, B and C
我想写一个应用过滤器的函数(例如A> 1),但A需要是动态的(函数的参数),所以如果我通知A,它A> 1;如果我通知B,它B> 1等等(当然,A和B总是列名)
I'd like to write a function that applies a filter (for example A>1) but "A" needs to be dynamic (the function's parameter) so if I inform A, it does A>1; If I inform B, it does B>1 and so on... (A and B always being the columns names, of course)
例如:
假设我的数据是下面的,我想做A == 1,它会返回绿线,或做B == 1& C == 1,并返回蓝线。
Example: Lets say my data is bellow, I'd like to do "A==1" and it would return the green line, or do "B==1 & C==1" and return the blue line.
>
这样做可以吗?
感谢
Can this be done? thanks
推荐答案
如果您的数据
a <- c(1:9)
b <- c(10:18)
# create a data.frame
df <- data.frame(a,b)
# or a data.table
dt <- data.table(a,b)
您可以将条件存储在变量 x
you can store your condition(s) in a variable x
x <- quote(a >= 3)
并使用 dplyr
(使用[]进行子集操作)
and filter the data.frame using dplyr
(subsetting with [] won't work)
library(dplyr)
filter(df, x)
或使用@Frank建议的 data.table
or using data.table
as suggested by @Frank
library(data.table)
dt[eval(x),]
这篇关于按动态列名过滤数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!