【问题标题】:Subset a data.frame using logical character strings使用逻辑字符串对 data.frame 进行子集
【发布时间】:2012-08-18 00:19:15
【问题描述】:

我想使用字符串执行逻辑运算(是的,我想这样做)

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

我希望使用如下字符串

  a[logical_text,]
> a[logical_text,]
    x  y
NA NA NA

为了得到相同的结果:

a[a$x!=2 & a$y!=14,]
> a[a$x!=2 & a$y!=14,]
  x  y
1 1 11
3 3 13

【问题讨论】:

    标签: r character dataframe subset


    【解决方案1】:

    以这种方式做事不一定是个好主意。但是如果你真的必须的话,你可以使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-27
      • 2021-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      • 2015-09-10
      相关资源
      最近更新 更多