简体   繁体   中英

R data.table filter column which name has space

I have a data.table. One of the column is called "High Score". I know we can always rename the column. But is there a way to subset the data based on the column if we have to use quote for the column name? Actually I need do that for a list of this type of columns

I have used iris table to made the following example:

library(data.table)

dt <- as.data.table(iris)

# rename to make the variable with space
setnames(dt, c("Sepal.Length", "Sepal.Width",  "Petal.Length", "Petal.Width",  "Species"), 
     c("Sepal Length", "Sepal Width",  "Petal Length", "Petal Width",  "Species")) 

seg_name <- c("Sepal Length", "Sepal Width",  "Petal Length", "Petal Width")

Then I want to create a number of subsets based on each column. But all these columns are with space or special char

for (i in 1:length(seg_name)){
  # here is the problem !!!
  tmp <- dt[seg_name[i] > 6]
  fwrite(tmp, paste0('./output/', seg_name[i], '.txt'), row.names = F, sep = "\t")
}

One cannot access column names with variable/character in i segment of a data.table . Instead you can opt to use get .

One can write the for-loop as:

for (i in 1:length(seg_name)){
  tmp <- dt[get(seg_name[i]) > 6] 
  fwrite(tmp, paste0('./output/', seg_name[i], '.txt'), row.names = F, sep = "\t")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM