列表列表中向量的均值 [英] Mean of vector inside of list of lists
本文介绍了列表列表中向量的均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个具有以下结构的列表列表:
I have a list of lists with the following structure:
> mylist <- list(list(a=as.numeric(1:3), b=as.numeric(4:6)),
list(a=as.numeric(6:8), b=as.numeric(7:9)))
> str(mylist)
List of 2
$ :List of 2
..$ a: num [1:3] 1 2 3
..$ b: num [1:3] 4 5 6
$ :List of 2
..$ a: num [1:3] 6 7 8
..$ b: num [1:3] 7 8 9
我想获得mylist
的向量a
和b
之间的逐元素均值.对于向量a
,结果将是这样:
I would like to get the element-wise mean between the vectors a
and b
of mylist
. For the vector a
, the result would be this:
> a
[1] 3.5 4.5 5.5
我知道函数lapply
,rbind
和colMeans
,但是我无法解决它们的问题.我该如何实现自己的需求?
I know the functions lapply
, rbind
and colMeans
but I can't solve the problem with them. How can I achieve what I need?
推荐答案
另一个想法:
tmp = unlist(mylist, F)
sapply(unique(names(tmp)),
function(x) colMeans(do.call(rbind, tmp[grep(x, names(tmp))])))
# a b
#[1,] 3.5 5.5
#[2,] 4.5 6.5
#[3,] 5.5 7.5
这篇关于列表列表中向量的均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文