[英]Access several elements from list based on the indexes stored in another list
What I am trying to do is to extract elements from data frame column that contains list, imagine column df$A with 3 rows, each rows contains list: 我想做的是从包含列表的数据帧列中提取元素,想象一下具有3行的df $ A列,每行包含list:
c(111, 222, 333)
c(444, 555, 666)
c(777, 888, 999)
(lists vary from one to twenty-thirty elements) (列表从1到23个元素不等)
while column df$B stores certain positions of elements: 而df $ B列存储元素的某些位置:
1
c(1, 2)
c(1, 2, 3)
my goal is to extract to column df$C elements from column df$B, based on their index stored in column df$A, so the column df$C would look like 我的目标是根据存储在df $ A列中的索引从df $ B列提取到df $ C列,因此df $ C列看起来像
111
c(444, 555)
c(777, 888, 999)
I've already tried different combinations of unlist, sapply, mutate, accessing list elements with vector, like 我已经尝试过unlist,sapply,mutate,使用vector访问列表元素的不同组合,例如
df$A[nrow][[c(df$B)]]
and so on, but I keep on running into different errors and haven't gotten closer to desired result. 依此类推,但我不断遇到不同的错误,而且还没有接近预期的结果。
Finally, what I want to achieve, is to sum integers in each row on certain position on a list, so potential df$D might look like 最后,我要实现的是对列表中特定位置的每一行中的整数求和,因此潜在的df $ D可能看起来像
111
999
2664
I am afraid that maybe my entire approach is wrong and I am forcing R to act in a way it was not designed to, but so far I usually managed to get right answers for every question I've asked myself. 恐怕我的整个方法可能是错误的,并且我正在强迫R以一种并非旨在的方式行事,但到目前为止,我通常可以对自己问的每个问题都能找到正确的答案。
not sure about the whole data.frame contains lists thing: 不确定整个data.frame是否包含列表项:
data: (not recommended though) just use two lists ( l1
, l2
) 数据:(尽管不建议使用)仅使用两个列表(
l1
, l2
)
df1 <- data.frame(A = 1:3)
df1$A <- list(c(111, 222, 333),
c(444, 555, 666),
c(777, 888, 999))
df1$B <- list(1,
c(1, 2),
c(1, 2, 3))
code: its time for ?mapply
. 代码:的时间为
?mapply
。
#df1$D <-
mapply(function(vals, inds) {sum(vals[inds])}, vals = df1$A, inds = df1$B)
result: 结果:
#[1] 111 999 2664
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.