Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element-wise mean in R

Tags:

r

mean

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.

like image 535
Zhang18 Avatar asked Aug 16 '10 21:08

Zhang18


People also ask

What is element wise in R?

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.

How do you find the mean of two vectors in R?

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.


3 Answers

how about:

rowMeans(cbind(a, b), na.rm=TRUE)

or

colMeans(rbind(a, b), na.rm=TRUE)
like image 100
Greg Avatar answered Sep 29 '22 23:09

Greg


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?

like image 23
deinst Avatar answered Sep 30 '22 00:09

deinst


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
like image 30
shosaco Avatar answered Sep 30 '22 00:09

shosaco