0
votes

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")
}
1
Use dt[`Sepal Length` > 3], don't overwrite subset, it's a base R functionpogibas
thanks for your response. but if I want to put it in a loop, how to do that?Gavin
@Gavin What is cust_seg_all?MKR
sorry, I updated.Gavin

1 Answers

0
votes

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")
}