Adam Sanders - 2 months ago 13
R Question

# R get row mean of every nth element in a list

I have a nested list and I want to get the mean of one particular variable inside the list.

When my list was not nested, it was simple to do, but I am not sure how to change my code now that there are multiple elements of different sizes
str of list:

``````> str(means2)
List of 1
\$ :List of 2
..\$ :'data.frame':    12 obs. of  2 variables:
.. ..\$ means        : num [1:12] 465063 355968 76570 542873 854570 ...
.. ..\$ variablenames: chr [1:12] "NumberOfPassengers" "FareClass" "TripType" "JourneyTravelTime" ...
..\$ :'data.frame':    12 obs. of  2 variables:
.. ..\$ means        : num [1:12] 449490 359997 67899 602895 967327 ...
.. ..\$ variablenames: chr [1:12] "NumberOfPassengers" "FareClass" "TripType" "JourneyTravelTime" ...
``````

I was using this code

``````testdf=as.data.frame(rowMeans(simplify2array(sapply(means2,"[[",1))))
``````

I am just not sure how to change this code to match the fact the means I am obtaining are from the 2nd element and not the first(only) element.

Thanks for any help

example:

Based on the `str` of the nested `list` for 'means2', this should work

``````unlist(lapply(means2, function(x) rowMeans(do.call(cbind, sapply(x, "[", 1)))))
``````

As there is only a single outer `list`, we can extract it using `[[`, loop over the `list` elements get the first column as vector, get the elementwise sum with `Reduce` and divide by the length of the `list` (in the example it is 2).

``````Reduce(`+`, lapply(means2[[1]], `[`, 1))/2
``````

Or after extracting the `list` elements, `cbind` it and do a `rowMeans`

``````rowMeans(do.call(cbind,lapply(means2[[1]], `[`, 1)))
``````

### data

``````means2 <- list(list(data.frame(means = 1:5, variablenames = letters[1:5]),
data.frame(means = 11:15, variablenames = letters[6:10])) )
``````