R: Extract Deeply Embedded Elements of List into Array
Question
I would like to extract elements from a deeply embedded list into an array.
For example, I am implementing a t-test at each grid point (2x2) and would like to save each p-value from the t-test into a 2x2 array without a nested for loop. (My data set is quite large.)
z <- rnorm(2*2*2)
z <- array(z, dim=c(2,2,2))
ttest <- apply(z, c(1,2), function(x) t.test(x, mu=.3, var.equal=TRUE))
ttest[[1,1]]$p.value # extracts p-value at the first grid point.
# This would be the [1,1] element in my desired array.
Solution
Do you want something like this:
> apply( ttest, 1:2, function(z) z[[1]]$p.value)
[,1] [,2]
[1,] 0.9030515 0.08736825
[2,] 0.7740801 0.35580602
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow