How to add two vectors WITHOUT repeating in R?

前端 未结 1 1426
日久生厌
日久生厌 2021-01-17 18:26

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.

Exam

相关标签:
1条回答
  • 2021-01-17 18:32

    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
    

    Or, as a function:

    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
    

    Here's another solution using rep:

    x <- c(x, rep(0, length(y)-length(x)))
    x + y
    
    0 讨论(0)
提交回复
热议问题