使用字符串访问 data.table 列 [英] Access data.table columns with strings

查看:15
本文介绍了使用字符串访问 data.table 列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个很明显我通常在 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!

在下面的一些有用的评论和提示之后,我想我已经缩小了问题的范围,并有了一个可重现的例子.考虑:

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 的列,即我循环 colnamecolnumber 然后访问列 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆