[R] Indexing a list with a list

Greg Hirson ghirson at ucdavis.edu
Fri Jun 26 20:27:06 CEST 2009


Dear list,

I have two lists: one with data and one with TRUE/FALSE values for data 
I want to further analyze (see example below). I have been able to use a 
for loop to extract the data that I want to keep, but think that there 
probably exists a way to do it without a loop. Any ideas?

#sample data
set.seed(100)
example = list(letters[1:10], letters[1:10], letters[1:10])
ind = list(as.logical(sample(0:1, 10, rep=TRUE)), as.logical(sample(0:1, 
10, rep=TRUE)), as.logical(sample(0:1, 10, rep=TRUE)), 
as.logical(sample(0:1, 10, rep=TRUE)))

#loop method
for (i in 1:length(example)) print(example[[i]][ind[[i]]])

#result
[1] "c" "g" "i"
[1] "a" "b" "e" "f" "j"
[1] "a" "b" "c" "d" "g" "h" "i"


Thank you for the help.

Greg

-- 
Greg Hirson
ghirson at ucdavis.edu

Graduate Student
Agricultural and Environmental Chemistry

1106 Robert Mondavi Institute North
One Shields Avenue
Davis, CA 95616




More information about the R-help mailing list