简体   繁体   English

如何将每个向量元素添加到 R 中的每个列表元素?

[英]How to add each vector element to each list element in R?

Reproducible example:可重现的例子:

A <- list(1,2,3)
B <- c(10,20,30)

I want to add each vector element of B to each list element with the same index.我想将 B 的每个向量元素添加到具有相同索引的每个列表元素中。 The expected result is:预期的结果是:

> AB
[[1]]
[1] 11

[[2]]
[1] 22

[[3]]
[1] 33

How to do this without using a loop?如何在不使用循环的情况下做到这一点?

Using Map .使用Map

Map(`+`, A, B)
# [[1]]
# [1] 11
# 
# [[2]]
# [1] 22
# 
# [[3]]
# [1] 33
purrr::map2(A, B, sum)

[[1]]
[1] 11

[[2]]
[1] 22

[[3]]
[1] 33

我想出了以下方法:

AB <- lapply(A, function(x) A[[x]] + B[x])

If the length of each element in the list is 1, it may be more efficient to unlist and do this once and relist back如果list中每个元素的长度为 1,则unlist并执行一次然后重新relist可能更有效

relist(unlist(A) + B, A)
[[1]]
[1] 11

[[2]]
[1] 22

[[3]]
[1] 33

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

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