在R中的data.table中,如何引用列名称中包含`<=`而不让R将其视为操作?

huangapple go评论68阅读模式
英文:

In data.table in R, how can you reference columns that have `<=` in their names without making R think its an operation?

问题

假设我们在R中有以下的data.table对象,我们希望按照x<=0.5 == 1的条件对数据进行子集操作:

x=rnorm(1000)
df <- data.table(x=x, `x<=0.5`=1*(x<=0.5))
df[`x<=0.5` == 1]

这会返回一个错误信息:

在一个'on'语句中找到了多个操作符:x<=0.5==x<=0.5。请指定一个单一的操作符。

我如何在不出现这个错误的情况下引用它?我认为问题出在它将小于或等于符号视为操作符而不是名称。

英文:

Suppose we have the following data.table object in R, and we wish to subset the data by those where x&lt;=0.5 == 1:

x=rnorm(1000)
df &lt;- data.table(x=x, `x&lt;=0.5`=1*(x&lt;=0.5))
df[`x&lt;=0.5` == 1]

This returns an error saying:

Error in .parse_on(substitute(on), isnull_inames): Found more than one operator in one &#39;on&#39; statement: x&lt;=0.5==x&lt;=0.5. Please specify a single operator.

How can I actually reference it without this error? I assume it is because it thinks the less than or equal sign is not a name but an operation.

答案1

得分: 2

使用 get 函数可以从字符串中获取值。

df[get("x<=0.5") == 1]

输出结果:

               x x<=0.5
  1:  0.3903123      1
  2:  0.1426477      1
  3: -0.3169492      1
  4: -1.3024570      1
  5: -1.5403663      1
 ---                  
691: -0.4453730      1
692: -2.3406638      1
693: -0.3276438      1
694:  0.4063935      1
695: -0.5860276      1

或者将它用在 .SDcols 中:

df[df[, .SD[[1]] == 1, .SDcols = "x<=0.5"]]
英文:

We may use get on a string to return the value

df[get(&quot;x&lt;=0.5&quot;) == 1]

-output

               x x&lt;=0.5
  1:  0.3903123      1
  2:  0.1426477      1
  3: -0.3169492      1
  4: -1.3024570      1
  5: -1.5403663      1
 ---                  
691: -0.4453730      1
692: -2.3406638      1
693: -0.3276438      1
694:  0.4063935      1
695: -0.5860276      1

Or use it in .SDcols

df[df[, .SD[[1]] == 1, .SDcols = &quot;x&lt;=0.5&quot;]]

</details>



huangapple
  • 本文由 发表于 2023年2月19日 10:08:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75497577.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定