I know this topic appeared on SO a few times, but the examples were often more complicated and I would like to have an answer (or set of possible solutions) to this simple situation. I am still wrapping my head around R and programming in general. So here I want to use lapply
function or a simple loop to data
list which is a list of three lists of vectors.
data1 <- list(rnorm(100),rnorm(100),rnorm(100)) data2 <- list(rnorm(100),rnorm(100),rnorm(100)) data3 <- list(rnorm(100),rnorm(100),rnorm(100)) data <- list(data1,data2,data3)
Now, I want to obtain the list of means for each vector. The result would be a list of three elements (lists).
I only know how to obtain list of outcomes for a list of vectors and
for (i in 1:length(data1)){ means <- lapply(data1,mean) }
or by:
lapply(data1,mean)
and I know how to get all the means using rapply
:
rapply(data,mean)
The problem is that rapply does not maintain the list structure. Help and possibly some tips/explanations would be much appreciated.
lapply returns a list of the same length as X , each element of which is the result of applying FUN to the corresponding element of X .
The lapply() function helps us in applying functions on list objects and returns a list object of the same length. The lapply() function in the R Language takes a list, vector, or data frame as input and gives output in the form of a list object.
The apply functions do run a for loop in the background. However they often do it in the C programming language (which is used to build R). This does make the apply functions a few milliseconds faster than regular for loops.
Almost all data in R is stored in a vector, or even a vector of vectors. A list is a recursive vector: a vector that can contain another vector or list in each of its elements. Lists are one of the most flexible data structures in R. As a result, they are used as a general purpose glue to hold objects together.
We can loop through the list of list with a nested lapply/sapply
lapply(data, sapply, mean)
It is otherwise written as
lapply(data, function(x) sapply(x, mean))
Or if you need the output with the list
structure, a nested lapply
can be used
lapply(data, lapply, mean)
Or with rapply
, we can use the argument how
to get what kind of output we want.
rapply(data, mean, how='list')
If we are using a for
loop, we may need to create an object to store the results.
res <- vector('list', length(data)) for(i in seq_along(data)){ for(j in seq_along(data[[i]])){ res[[i]][[j]] <- mean(data[[i]][[j]]) } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With