I have a list of data.table objects that all have a similar name and some property that I would like to change on all of them by looping through this list. Let's consider this:
set.seed(999)
GenName_ksio3k_F1 <-data.table(Risknr = runif(10,1000,9999), Code=LETTERS[sample.int(10)], val=rnorm(10));GenName_ksio3k_F1
GenName_kf0bner_F6 <-data.table(Risknr = runif(10,1000,9999), Code=LETTERS[sample.int(10)], val=rnorm(10));GenName_kf0bner_F6
GenName_sjkw_F2 <-data.table(Risknr = runif(10,1000,9999), Code=LETTERS[sample.int(10)], val=rnorm(10));GenName_sjkw_F2
So as suggested by this naming, these objects have similar names which I can capture conveniently in a list via regular expression:
list = grep("^(GenName_).*(F[0-9])$", ls(), perl=TRUE, value=TRUE);list
Now, what I would like to to do is change the column Risknr to a factor variable on all of these tables. I tried this:
for(DT in list){
print(str(eval(parse(text = DT)))) # as a test
eval(parse(text = DT))$Risikonr <- as.factor(eval(parse(text = DT$Risikonr)
}
accessing the variable seems to work, as printing str for each DT shows. The as.factor-conversion looks wrong and of course does not work.
But how to do this?
lapply(list, function(i) {i$Risknr <- as.factor(i$Risknr);i})list2env(lapply(mget(list), function(x) x[, Risknr := factor(Risknr)]))