data.table operations by column name with spaces fails

后端 未结 1 1886
既然无缘
既然无缘 2021-02-09 16:26

Reproducible example

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


        
1条回答
  •  太阳男子
    2021-02-09 17:22

    Update 2020-04-22

    data.table has evolved and now iris[ , 'Petal.Length'] will return a one-column table (i.e., character and integer literal vectors in j can be used for column selection). There have also been ample updates in extending .SDcols for common use cases to do column filtration (subsetting by pattern on name, subsetting by logical aggregation); see the NEWS for more details.

    Leaving the below for posterity.


    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.
    

    0 讨论(0)
提交回复
热议问题