【发布时间】:2021-07-23 15:12:46
【问题描述】:
有趣的是,我找不到使用列号进行过滤的方法。我不知道列的名称,因为它会更改名称,但我总是知道列的位置。
这看起来很简单,但似乎我只能使用列名引用 i 部分。
table = data.table(one = c(1,2,3), two = c("a","b","c"))
> table
one two
1: 1 a
2: 2 b
3: 3 c
我不知道第二列是“二”。我只想按第二列过滤。
> table[two == "a"]
one two
1: 1 a
更新:
正如 Ronak 所说,我可以使用
> table[table[[2]]=="a"]
one two
1: 1 a
但是我接下来想更新同一列,例如我想将“a”变成“c”。
我需要什么:
> table
one two
1: 1 c
2: 2 b
3: 3 c
我试过了:
> table[table[[2]]=="a", table[[2]]:= "c"]
> table
one two a b c
1: 1 a c c c
2: 2 b <NA> <NA> <NA>
3: 3 c <NA> <NA> <NA>
所以看起来我正在获取第二列中的所有值并为它们创建新列,而不是仅仅将过滤后的行更改为 c。
> table[table[[2]]=="a", table[2]:= "c"]
Error in `[.data.table`(table, table[[2]] == "a", `:=`(table[2], "c")) :
LHS of := must be a symbol, or an atomic vector (column names or positions).
所以我想我需要知道第二列的位置。
【问题讨论】:
-
感谢 Ronak,我实际上是在您发布此内容时对其进行编辑!
标签: r data.table