In R, I have two vectors:
a <- c(1, 2, 3, 4)
b <- c(NA, 6, 7, 8)
How do I find the element-wise mean of the two vectors, removing NA, without a loop? i.e. I want to get the vector of
(1, 4, 5, 6)
I know the function mean()
, I know the argument na.rm = 1
. But I don't know how to put things together. To be sure, in reality I have thousands of vectors with NA appearing at various places, so any dimension-dependent solution wouldn't work. Thanks.
R Language Subsetting Elementwise Matrix OperationsThe operators + , - , / , * , ^ when used with matrices of same dimension perform the required operations on the corresponding elements of the matrices and return a new matrix of the same dimension. These operations are usually referred to as element-wise operations.
The mean is calculated by taking a sum of the values and dividing by the number of values in the data. If the data series is a vector, the mean is calculated by taking a sum of vector elements and dividing by the number of elements of the series. To calculate the mean in R, use an inbuilt mean() function.
how about:
rowMeans(cbind(a, b), na.rm=TRUE)
or
colMeans(rbind(a, b), na.rm=TRUE)
I'm not exactly sure what you are asking for, but does
apply(rbind(a,b),2,mean,na.rm = TRUE)
do what you want?
A tidyverse
solution usign purrr
:
library(purrr)
a <- c(1, 2, 3, 4)
b <- c(NA, 6, 7, 8)
# expected:
c(1, 4, 5, 6)
#> [1] 1 4 5 6
# actual:
map2_dbl(a,b, ~mean(c(.x,.y), na.rm=T)) # actual
#> [1] 1 4 5 6
And for any number of vectors:
> pmap_dbl(list(a,b, a, b), compose(partial(mean, na.rm = T), c))
[1] 1 4 5 6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With