简体   繁体   English

将向量的每个元素添加到另一个向量

[英]Add each element of vector to another vector

I have 2 vectors 我有2个向量

x <- c(2,2,5)
y <- c(1,2)

I want to add each element of the vectors together to get 我想将向量的每个元素组合在一起得到

[1] 3 3 6 4 4 7

How can I do this? 我怎样才能做到这一点?

We can use outer with FUN as + 我们可以使用FUN outer作为+

c(outer(x, y, `+`))
#[1] 3 3 6 4 4 7

You can try creating each pair of x/y elements with expand.grid and then computing the row sums: 您可以尝试使用expand.grid创建每对x / y元素,然后计算行总和:

rowSums(expand.grid(x, y))
# [1] 3 3 6 4 4 7

You can also use variations of rep with + : 您还可以使用的变化rep+

rep(x, length(y)) + rep(y, each=length(x))
[1] 3 3 6 4 4 7

The second argument to + uses the each argument to rep which repeats each element of y corresponding to the length of x. +的第二个参数使用rep的每个参数重复y的每个元素,对应于x的长度。

或者您可以尝试:

as.vector(sapply(y,function(i) (i+x)))

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

相关问题 将一个向量与另一个向量的每个元素进行比较 - Comparing a vector against each element of another vector 将向量的每个元素与R中的另一个向量组合 - Combine each element of a vector with another vector in R R - 简洁地向每个向量元素添加向量 - R - Concisely add vector to each vector element 将序列添加到向量的每个元素 - Add sequence to each element of a vector 将向量的每个元素与另一个向量的每个元素连接起来 - Concatenate each element of a vector with each element of another vector 将每个元素添加到一个向量中,每个元素放在第二个向量中 - Add each element in one vector with each element in a second vector 将向量的每个元素与另一个向量的每个元素相加,得出总和向量 - Adding each element of a vector to each element of another vector to come up with a vector of sums 给定一个向量,将一个函数应用于另一个向量的每个元素 - Given a vector, apply a function to each element of another vector 如何计算向量中每个元素的另一个向量中较小的元素的分数? - How to calculate for each element in a vector the fraction of elements in another vector that is smaller? 找到一个向量和另一个向量的每个元素之间的最小差异 - Finding the minimum difference between each element of one vector and another vector
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM