【问题标题】:data.table - subsetting based on variable whose name is a column, toodata.table - 基于名称为列的变量的子集
【发布时间】:2016-11-16 20:24:33
【问题描述】:

这可能有点奇怪,但我在使用 data.table 的函数中使用其参数进行过滤时经常遇到这种情况。

假设您有一个变量,您想将其值与data.table 的列进行比较并进行过滤。如果变量名与列名相同怎么办?

示例和我尝试过的事情:

DT <- data.table(mtcars)
cyl <- 4
# intended: filter rows where column "cyl" equals the value of variable cyl

# this does not work
DT[cyl == (cyl)]
# this does not work either
DT[cyl == `cyl`]

【问题讨论】:

  • 相关帖子herehere
  • @Henrik 是的,这些 :)
  • @paljenczy 那是因为通常而且肯定在 r 中“过滤”被称为“子集”:)
  • 谢谢,改了标题。

标签: r data.table


【解决方案1】:

Data.table 正确运行在数据表本身的环境中,因此您可能需要指定要从何处获取值

DT[cyl == get("cyl", envir = parent.frame())]

【讨论】:

  • 这能回答你的问题吗?
【解决方案2】:

只需指定范围:

DT[cyl == globalenv()$cyl]

【讨论】:

    猜你喜欢
    • 2013-06-09
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    • 2019-09-07
    相关资源
    最近更新 更多