Gravity Kills
Gravity Kills

Reputation: 99

Filter Data Table on a list of lists

I'm creating multiple subsets of a data source that then gets graphed in a couple different ways and output to a pdf. I created a for loop to create everything and manipulate the data however when I try to subset, the data sets returned are empty. I've created a simple example showing the problem I'm having below.

Is there a different way I should be thinking about this?

id <- c(rep("a",20),rep("c",10),rep("d",10),rep("e",20),rep("f",20),rep("g",20))
x <- rnorm(n=100, mean=1323, sd=6.432)
dt <- data.table(id, x)

class1 <- c("a","e","g")
class2 <- c("c","F")
class3 <- c("b","d")

classes <- list(class1,class2,class3)

dtNames <- c("c1","c2","c3")

#this doesn't work
for(i in 1:length(classes)){
  assign(dtNames[i],dt[dt$id %in% classes[i],])
}

#this does work
assign(dtNames[1],dt[dt$id %in% class1])

Upvotes: 1

Views: 44

Answers (1)

akrun
akrun

Reputation: 887148

We need to use [[ to extract the list elements

for(i in seq_along(classes)){
  assign(dtNames[i], dt[id %chin% classes[[i]]])
 }

NOTE: It is better not to create multiple objects in the global environment.

Upvotes: 1

Related Questions