data.table操作与列名称与空格失败 [英] data.table operations by column name with spaces fails

查看:166
本文介绍了data.table操作与列名称与空格失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可重现的示例

 #使用Iris数据集
库table)
iris
colnames(iris)[3]< - - Petal Length
iris< - as.data.table(iris)
  

iris [,Petal.Width]

但是访问名称包含空格的列不起作用

  iris [,Petal Length] 
iris [,'Petal Length']

唯一的解决方案似乎是

  iris [,iris $'Petal Length'] 

评论 $ b我是新的data.table。我明白data.table中有很多奇怪的地方;是这一个吗?我会更改我的变量名称以摆脱空格,但我不喜欢如果我不需要。我还读了以前关于列名的问题 - 我知道在最后一个问题更新后的两年里,这是可以看出,当列名没有空格时。

解决方案

只需使用 with = FALSE http://datatable.r-forge.r-project.org/datatable-faq.pdf\">data.table常见问题点1.1-1.3和2.17:

  iris [,'Petal Length',with = FALSE] 


$ b b

,并请务必阅读出色的 data.table PDF小插图和新HTML小插图






在这种情况下,对于你期望的(向量),使用 [[更合适:

  iris [['Petal Length']] 

或者,您还可以引用列名称,如同他们是 j

  iris [,`Petal Length`] 


Reproducible example

#Use the Iris data set
library(data.table)
iris 
colnames(iris)[3] <- "Petal Length"
iris <- as.data.table(iris)

Accessing column without space is fine

iris[,Petal.Width]

however access a column where the name contains a space doesn't work

iris[,Petal Length]
iris[,'Petal Length']

The only solution seems to be

iris[,iris$'Petal Length']

Comments I'm new to data.table. I understand there's a lot of quirks in data.table; is this one of them? I would change my variable names to get rid of spaces, but I'd prefer not to if i didn't need to. I also read a previous questions regarding just column names - and I understand in the two years since that last question updates have allowed it - this can be seen in the ease when the colname has no spaces.

解决方案

Just use with = FALSE as explained under data.table FAQ points 1.1-1.3 and 2.17:

iris[ ,'Petal Length', with = FALSE]

and make sure to read the excellent introduction to data.table PDF vignette and the new HTML vignettes.


In this case, for what you expect (a vector), using [[ is more appropriate:

iris[['Petal Length']]

Alternatively, you can also refer to column names as if they were variables in j:

iris[, `Petal Length`] # note the backticks.

这篇关于data.table操作与列名称与空格失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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