Yang Yang
Yang Yang

Reputation: 902

How to average every 3 columns with NA in R

I have a matrix with NA and I want to find the mean of every 3 columns for each row.

set.seed(100)
a <- matrix(sample(c(NA, 1:4), 90, replace = TRUE), 10)

If I use

t(apply(a, 1, tapply, gl(3, 3), mean))

The code cannot find the average for colums including NA. I wonder how I can modify the code. Thanks a lot.

Upvotes: 1

Views: 579

Answers (1)

akrun
akrun

Reputation: 887241

We can do this by also converting to a 3D array and then get the rowMeans after looping through the 3rd MARGIN.

res <- apply(array(a, c(nrow(a), 3, 3)), 3, rowMeans, na.rm = TRUE)
all.equal(res, t(apply(a, 1, tapply, gl(3, 3), 
       mean, na.rm = TRUE)), check.attributes = FALSE)
#[1] TRUE

Upvotes: 1

Related Questions