嗨,我
正在使用一个大型数据框,我经常需要在不同的变量组合中进行子集化。我希望能够将搜索存储在字符串中,以便在我想查看子集时可以引用字符串。
x = read.table(textConnection("
cat1 cat2 value
A Z 1
A Y 2
A X 3
B N 2"),header=T,strip.white=T)
search_string="cat1== 'A' & cat2=='Z'"
with(x,subset(x,search))
不行。我要寻找的是类似于下面的搜索结果。
with(x,subset(x,cat1=='A' & cat2=='Z'))
如果存在其他解决方案,我不希望在开始时创建多个子集数据框。
有没有一种简单的方法来做我正在尝试的事情?
您需要将字符串转换为表达式,然后计算此表达式
subset(x, eval(parse(text=search_string)))
cat1 cat2 value
1 A Z 1
永远记住
fortune(106) If the answer is parse() you should usually rethink the question. -- Thomas Lumley R-help (February 2005) fortune(181) Personally I have never regretted trying not to underestimate my own future stupidity. -- Greg Snow (explaining why eval(parse(...)) is often suboptimal, answering a question triggered by the infamous fortune(106)) R-help (January 2007)
并注意在这种情况下,去 eval(parse(text==))) 的打字要多得多)
您也可以尝试使用 quote
来保存call
search <- quote(cat1== 'A' & cat2=='Z')
然后只需使用
subset(x, eval(search))
同样重要的是要记住,该subset
具有非标准评估,因此使用`[`
可能更安全
x[eval(search,x),]
或
x[eval(parse(text=search_string)), x),]