[R] indexing an array of lists: any nicer way?
Marius Hofert
m_hofert at web.de
Fri May 20 09:10:26 CEST 2011
Dear expeRts,
I'm struggling a bit with arrays of lists. The nice thing about arrays is that one can easily access subsets. For example:
arr. <- array(1:24, dim=c(2,3,4), dimnames=list(a=c("a1","a2"), b=c("b1","b2","b3"),
c=c("c1","c2","c3","c4")))
arr.[,,4]
mean(arr.[,,4]) # => easy to access all components for fixed third component
Assume we have an array of lists, where the second list components are numeric. For example:
a <- c("a1","a2")
b <- 1:3
c <- c("c1","c2","c3","c4")
arr <- array(list(), dim=c(length(a), length(b), length(c)),
dimnames=list(a=a, b=c("b1","b2","b3"), c=c))
for(i in 1:length(a)){
for(j in 1:length(b)){
for(k in 1:length(c)){
arr[i,j,k][[1]] <- list(a=a[i], b=b[j], c=c[k])
}
}
}
Assume further we want to compute the mean over all second components. But accessing them is not as trivial as before:
h <- sapply(arr[,,4], `[[`, 2) # pick out second components for fixed third component; not even sure if this is fully correct though
mean(h)
The question is if there is a nicer way to compute h, that is to access all second components in the lists?
Cheers,
Marius
More information about the R-help
mailing list