简体   繁体   English

R获取列表中每个第n个元素的行平均值

[英]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 的元素:

> 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: edited: example had an error示例:已编辑:示例有错误

Based on the str of the nested list for 'means2', this should work基于'means2'的嵌套liststr ,这应该有效

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).由于只有一个外部list ,我们可以使用[[提取它,循环list元素将第一列作为向量,使用Reduce获取元素总和并除以list的长度(在示例中为 2 )。

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

Or after extracting the list elements, cbind it and do a rowMeans或者在提取list元素后, cbind它并做一个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])) )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM