Combining two vectors element-by-element

前端 未结 3 1514
孤城傲影
孤城傲影 2020-12-19 04:55

I have 2 vectors, such as these:

A <- c(1,2,NA,NA,NA,NA,7)
B <- c(NA,NA,3,4,NA,NA,7)

I would like to combine them so that the resulti

相关标签:
3条回答
  • 2020-12-19 05:32

    These commands create the vector:

    X <- A
    X[is.na(A)] <- B[is.na(A)]
    X[is.na(B)] <- A[is.na(B)]
    X[!is.na(A & B)] <- -1
    
    #[1]  1  2  3  4 NA NA -1
    
    0 讨论(0)
  • 2020-12-19 05:43
    A <- c(1,2,NA,NA,NA,NA,7)
    B <- c(NA,NA,3,4,NA,NA,7)
    C <- rowMeans(cbind(A,B),na.rm=TRUE)
    C[which(!is.na(A*B))]<- -1
    #[1]   1   2   3   4 NaN NaN  -1
    

    Benchmarks:

    Unit: microseconds
              expr    min     lq median     uq     max
    1 Roland(A, B) 17.863 19.095 19.710 20.019  68.985
    2   Sven(A, B) 11.703 13.243 14.167 14.783 100.398
    
    0 讨论(0)
  • A bit late to the party, but here is another option defining a function that works by applying rules to the two vectors cbind-ed together.

    # get the data
    A <- c(1,2,NA,NA,NA,NA,7)
    B <- c(NA,NA,3,4,NA,NA,7)
    
    # define the function
    process <- function(A,B) {
      x <- cbind(A,B)
      apply(x,1,function(x) {
        if(sum(is.na(x))==1) {na.omit(x)} else
        if(all(is.na(x))) {NA} else
        if(!any(is.na(x))) {-1}
      })
    }
    
    # call the function
    process(A,B)
    #[1]  1  2  3  4 NA NA -1
    

    The main benefit of using a function is that it is easier to update the rules or the inputs to apply the code to new data.

    0 讨论(0)
提交回复
热议问题