Thursday, 15 January 2015

r - indexing through values of a nested list using mapply -



r - indexing through values of a nested list using mapply -

i have list of lists, each sub-list containing 3 values. goal cycle through every value of nested list in systematic way (i.e. start list 1, go through 3 values, go list 2, , on), applying function each. function hits missing values , breaks , i've traced problem indexing itself, doesn't behave in way expecting. lists constructed as:

pop <- 1:100 treat.temp <- null treat <- null ## generate 5 samples of pop (i in 1:5){ treat.temp <- sample(pop, 3) treat[[i]] <- treat.temp } ## create list index mapply iterations <- (1:5)

illustrative function , results.

test.function <- function(j, k){ (n in 1:3){ print(k[[n]][j]) } } results <- mapply(test.function, iterations, treat) [1] 61 [1] 63 [1] 73 [1] na [1] na [1] na [1] na [1] na <snipped>

for first cycle through 'j', works. after throws nas. if manually, returns values expect.

> print(treat[[1]][1]) [1] 61 > print(treat[[1]][2]) [1] 63 > print(treat[[1]][3]) [1] 73 > print(treat[[2]][1]) [1] 59 > print(treat[[2]][2]) [1] 6 > print(treat[[2]][3]) [1] 75 <snipped>

i'm sure basic question, can't seem find right search terms find reply here or on google. in advance!

edited add: mrflick's reply works problem. have multiple list inputs (hence mapply) in actual use. more detailed example, few notes.

pop <- 1:100 years <- seq.int(2000, 2014, 1) treat.temp <- null treat <- null year.temp <- null year <- null ## generate 5 samples of treated states, command states , treatment years (i in 1:5){ treat.temp <- sample(pop, 20) treat[[i]] <- treat.temp year.temp <- sample(years, 1) year[[i]] <- year.temp } ## create list index mapply iterations <- (1:5) ## define function test.function <- function(j, k, l){ (n in 1:3){ ## cycles treat through each value of jxn print(k[n]) ## holds treat (k) fixed each 3 cycle set of n (using first value in each treat sub-list); cycles through sub-lists j changes print(k[1]) ## same above, 2nd value in each sub-list of treat print(k[2]) ## holds year (l) fixed each 3 cycle set of n, cycling through values of year each time j changes print(l[1]) ## functionally equivalent print(l) } } results <- mapply(test.function, iterations, treat, year)

well, might misunderstanding how mapply works. function loop through both of iterations pass parameters, means treat subset each iteration. essentially, functions beingness called are

test.function(iterations[1], treat[[1]]) test.function(iterations[2], treat[[2]]) test.function(iterations[3], treat[[3]]) ...

and seem treat k variable if entire list. also, have indexes backwards well. test working, can do

test.function <- function(j, k){ (n in 1:3) print(k[n]) } results <- mapply(test.function, iterations, treat)

but isn't super awesome way iterate list. trying accomplish?

r mapply

No comments:

Post a Comment