Combining two vectors element-by-element

前端 未结 3 1513
孤城傲影
孤城傲影 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: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
    

提交回复
热议问题