Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Reduce function. Na treatment

Tags:

list

r

na

I have a question regarding the Reducefunction. For example i have a list that one of the elements has an NA.

a<-list(c(1,2),c(2,2),c(1,NA))

I wish to use the Reduce function to do an average of the elements of the list.

that is (1+2+1)/3=1.33 and (2+2+NA)/3 = NA But in this last case, what i actually need is to avoid having the NA so the result should be (2+2)/2 = 2so the final outcome is a vector 1.33, 2

I am using Reduce("+", a)/length(a) but i get an NA because of the NA element.

Thanks in advance

like image 868
donpresente Avatar asked Mar 01 '26 02:03

donpresente


1 Answers

I wouldn't use Reduce for this. It is just a hidden for loop anyway. Here is a better alternative:

rowMeans(do.call(cbind, a), na.rm = TRUE)
#[1] 1.333333 2.000000

This combines your vectors into a matrix and calculates the row means using the rowMeans function, which can remove NA values.

like image 152
Roland Avatar answered Mar 03 '26 15:03

Roland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!