We can use rowMeans
after cbind
ing the vectors 'b', 'c' to create a matrix
. rowMeans
have options (na.rm = TRUE
) to handle NA
values.
rowMeans(cbind(b,c), na.rm=TRUE)
Or colMeans
after rbind
ing the vectors.
colMeans(rbind(b,c), na.rm=TRUE)
Suppose if we have matrices instead of vectors, we can still do the rowMeans/colMeans
after looping through the columns/rows of one of the dataset (assuming that they are of the same dimension). For example,
b <- matrix(c(1,4,3, NA, 2, 3, NA, 2), ncol=2)
c <- matrix(c(NA, 4, 3, 8, 1, NA, 3, 4), ncol=2)
We loop though the column sequence (seq_len(ncol(b))
) with sapply
, cbind
the corresponding columns of 'b' and 'c' and get the rowMeans
. The output will be matrix
of the same dimension of the initial matrices.
m1 <- sapply(seq_len(ncol(b)), function(i)
rowMeans(cbind(b[,i], c[,i]), na.rm=TRUE))
m1
# [,1] [,2]
#[1,] 1 1.5
#[2,] 4 3.0
#[3,] 3 3.0
#[4,] 8 3.0
Another option instead of looping would be to replace the NA
elements in both datasets with 0
. We can use replace
for that, do the +
and divide based on the count of NA
elements for each position.
m2 <- (replace(b, which(is.na(b)), 0) + replace(c, which(is.na(c)), 0))
m2/(2-(is.na(b)+is.na(c)))
# [,1] [,2]
#[1,] 1 1.5
#[2,] 4 3.0
#[3,] 3 3.0
#[4,] 8 3.0
The above code can be made more compact by using NAer
from library(qdap)
library(qdap)
(NAer(b) + NAer(c))/(2-(is.na(b)+is.na(c)))
# 1 2
#1 1 1.5
#2 4 3.0
#3 3 3.0
#4 8 3.0