I have 5 columns of numeric data (m1, m2, m3, m4, m5), and I want to generate a new column with the average of all m in the same row. I.e:
(m1 + m2 + m3 + m4 + m5)/5
I have a problem managing NA values: I want the average to be NA if and only if all individual m values are NA. But, if I use na.rm, then NA are replaced with zeros, and NA is not in the funds column. On the other hand, if I do not use na.rm, then the column of values is NA, if ANY of m is NA.
I have done the following:
m <- rowSums(data.frame(m1,m2,m3,m4,m5)/5, na.rm=TRUE)
for (i in 1:length(m)) {
if ( all(is.na(c(m1[i],m2[i],m3[i],m4[i],m5[i])))) {
m[i] <- NA
}
}
This works, but I'm pretty sure that R can do it better. How can this be done without cycles?
Perhaps the question sounds a little trivial. Sorry for that, but I'm new to R.
Thanks in advance.