如何添加两个向量而不在R中重复? [英] How to add two vectors WITHOUT repeating in R?
本文介绍了如何添加两个向量而不在R中重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 R 中有两个不同大小的向量,我想将它们相加,但不重复较短的一个 - 相反,我希望缺失"的数字为零.
I have two vectors in R of different size, and I want to add them, but without repeating the shorter one - instead, I want the "missing" numbers to be zeroes.
示例:
x<-c(1,2)
y<-c(3,4,5)
z<-x+y
现在,z
是 4 6 6
,但我只想要 4 6 5
.
Now, z
is 4 6 6
, but I want it only 4 6 5
.
推荐答案
我会让它们等长然后添加它们:
I would make them equal length then add them:
> length(x) <- length(y)
> x
[1] 1 2 NA
> x + y
[1] 4 6 NA
> x[is.na(x)] <- 0
> x + y
[1] 4 6 5
或者,作为一个函数:
add.uneven <- function(x, y) {
l <- max(length(x), length(y))
length(x) <- l
length(y) <- l
x[is.na(x)] <- 0
y[is.na(y)] <- 0
x + y
}
> add.uneven(x, y)
[1] 4 6 5
鉴于您只是将两个向量相加,像这样使用它可能更直观:
Given that you're just adding two vectors, it may be more intuitive to work with it like this:
> `%au%` <- add.uneven
> x %au% y
[1] 4 6 5
这是使用 rep 的另一种解决方案:
Here's another solution using rep:
x <- c(x, rep(0, length(y)-length(x)))
x + y
这篇关于如何添加两个向量而不在R中重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文