使用字符串访问data.table列 [英] Access data.table columns with strings
问题描述
很抱歉,这个问题很明显地表明我通常在Python / pandas中工作,但我对此一无所知。如何使用字符串选择 data.table
列?
Apologies for a question that probably makes it obvious that I usually work in Python/pandas, but I'm stuck with this. How do I select a data.table
column using a string?
dt$"string"
dt$as.name("string")
dt$get("string")
我确定这是非常简单的,但我没有。
I'm sure this is super simple, but I'm not getting it. Any help is greatly appreciated!
在以下一些有用的评论和提示之后,我想ve缩小了问题的范围,并提供了可重复的示例。考虑:
After some of the helpful comments and tips below, I think I've narrowed down the problem a bit and have a reproducible example. Consider:
dt = data.table(ID = c("a","a","a","b","b","b"), col1=rnorm(6), col2=rnorm(6)*100)
并假设我们要将 col2
中的值分配给 col1
。正如我在下面了解到的那样, data.table
的语法将是 dt [,col1:= col2]
,干净简单。当 j
参数中的一个(或两个)变量是字符串时,问题就开始了。我发现了以下内容:
And assume we want to assign the values in col2
to col1
. As I've learned below, the data.table
syntax for this would be dt[,col1:=col2]
, clean and simple. The problems start when one (or both) of the variables in the j
argument are strings. I found the following:
dt [, col1:= col2]
可以正常工作
dt [, col1:= col2]
失败(尝试分配字符 col2
到对偶向量 col1
dt[, "col1":="col2"]
fails as expected (tries to assign the character col2
to the double vector col1
dt [ , col1:= get( col2)]
正常工作
dt [,get( col1)]
返回预期的 col1
但是: dt [,get( col1):= col2]
或其他分配失败。
but: dt[, get("col1"):=col2]
or any other assignment fails.
某些情况:这样做的原因是我在循环中构造字符串,以访问大量都命名为 colname_colnumber
的列,即我遍历 colname
和 colnumber
来访问列 paste0(colname,colnumber)
。
Some context: the reason for doing this is that I'm constructing strings in a loop, to access a larger number of columns that are all named colname_colnumber
, i.e. I loop over colname
and colnumber
to then access column paste0(colname,colnumber)
.
推荐答案
您可以将 get()
用作 j
参数使用单括号:
You can use get()
as the j
argument using single brackets:
library(data.table)
dt <- data.table(iris)
dt[, get("Species")]
结果:
[1] setosa setosa setosa setosa setosa setosa .....
您也可以在双括号运算符内直接使用字符串,如下所示:
You can also use a string directly inside the double bracket operator, like this:
dt[["Species"]]
这篇关于使用字符串访问data.table列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!