mma*_*123 0 r character subset dataframe
我想使用字符串执行逻辑操作(是的,我想这样做)
a = data.frame(x=c(1,2,3,4),y=c(11,12,13,14))
logical_text = "a$x!=2 & a$y!=14"
a
> a
x y
1 1 11
2 2 12
3 3 13
4 4 14
Run Code Online (Sandbox Code Playgroud)
我希望使用如下字符串
a[logical_text,]
> a[logical_text,]
x y
NA NA NA
Run Code Online (Sandbox Code Playgroud)
为了得到相同的结果:
a[a$x!=2 & a$y!=14,]
> a[a$x!=2 & a$y!=14,]
x y
1 1 11
3 3 13
Run Code Online (Sandbox Code Playgroud)
以这种方式做事并不一定是个好主意.但是,如果你真的必须使用它eval(parse(text = your_command_as_a_string_here))来评估一个字符串,就像它是代码一样
a = data.frame(x=c(1,2,3,4),y=c(11,12,13,14))
logical_text = "a$x!=2 & a$y!=14"
# Evaluate logical_text into a temporary logical variable
logical_output <- eval(parse(text = logical_text))
a[logical_output,]
# x y
#1 1 11
#3 3 13
# Same thing but without storing as a temporary variable.
a[eval(parse(text=logical_text)), ]
# x y
#1 1 11
#3 3 13
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
703 次 |
| 最近记录: |