1

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])
Gravity Kills
  • 99
  • 2
  • 2
  • 6
  • It is better not to create multiple objects in the global environment – akrun Dec 30 '16 at 15:49
  • It is better to create lists of data.frames rather than use assign. See @gregor's post on [this question](http://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames) for tips on creating and working with such objects. – lmo Dec 30 '16 at 16:10

1 Answers1

1

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.

akrun
  • 674,427
  • 24
  • 381
  • 486
  • 1
    I'm not using the assign command in my actual code, I'm just throwing the filtered data set into a list which I then pull from to run through other functions. Thanks for your help! – Gravity Kills Dec 30 '16 at 16:11