Iterating over separate lists in R -
i have lots of variables in r, of type list
a100 = list() a200 = list() # ... p700 = list() each variable complicated data structure:
a200$time$data # returns 1000 x 1000 matrix now, want apply code each variable in turn. however, since r doesn't support pass-by-reference, i'm not sure do.
one idea had create big list of these lists, i.e.,
biglist = list() biglist[[1]] = a100 ... and iterate on biglist:
for (i in 1:length(biglist)){ biglist[[i]]$newstuff = "profit" # more code here } and finally, after loop, go backwards existing code (that uses variable names) still works:
a100 = biglist[[1]] # ... the question is: there better way iterate on set of named lists? have feeling i'm doing things horribly wrong. there easier, like:
# fake, idealized code: foreach x in (a100, a200, ....){ x$newstuff = "profit" } a100$newstuff # "profit"
to parallel walk on lists can use mapply, take parallel lists , walk on them in lock-step. furthermore, in functional language should emit object want rather modify data structure within function call.
you should use sapply, apply, lapply, ... family of functions.
jim
Comments
Post a Comment