[英]Process vector nested within a nested list in R
I have a list
of list
s of vector
s like the following: 我有一个
vector
list
的list
,如下所示:
myList = list(id1 = list(a=6:10,b=1:5),
id2 = list(a=3:8,b = 4:9))
I would like to process the second vector
named 'b' in each list with an arbitrary function
(eg, mean
, sum
, etc.) and append the result to a third named vector
within each nested list
to achieved something like: 我想在每个列表中使用任意
function
(例如, mean
, sum
等)处理名为“b”的第二个vector
,并将结果附加到每个嵌套list
的第三个命名vector
,以实现类似于:
myList2 = list(id1 = list(a=6:10,b=1:5,c = mean(1:5)),
id2 = list(a=3:8,b = 4:9,c = mean(4:9)))
Thus, my question has two parts. 因此,我的问题有两个部分。 First, how can I process only the second named
vector
in each nested list
? 首先,如何在每个嵌套
list
中仅处理第二个命名vector
? Second, how can I append the result to each nested list
? 其次,如何将结果附加到每个嵌套
list
?
I know I can write a for
loop that always indexes myList[[i]][[2]]
, but I am looking for a vectorized solution. 我知道我可以编写一个始终索引
myList[[i]][[2]]
的for
循环,但我正在寻找一个矢量化解决方案。 I've tried using various combinations apply
-family with an anonymous function
that first tests the name of the vector
, for example: 我尝试使用各种组合
apply
-family与首先测试vector
名称的匿名function
,例如:
rapply(myList, function(x) ifelse(names(x) == "b",
print("yes"), #process vector
print("no")), #move on to next x
how = "list"
)
but the result doesn't make much sense. 但结果没有多大意义。
Additional information: I'm using nested list
s instead of a data.frame
because I don't have the same number of observations for each id, but I am open to alternative approaches that might bypass these issues and accommodate different numbers of observations. 附加信息:我使用嵌套
list
而不是data.frame
因为我对每个id没有相同数量的观察,但我愿意接受可能绕过这些问题并适应不同数量观察的替代方法。
This should do it 这应该做到这一点
lapply(myList, function(x) {
x$c <- mean(x$b)
return(x)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.