I am trying to take the average score for each name. I would like to add up the scores values (omitting NA
s) and then divide by the number of values. I have gotten the sum, but am struggling with how to divide by the number of values that are not `NA.
Here is some example code:
names <- c("d", "e", "f", "g")
score.a.ALL <- c(1, 2, NA, 3)
score.b.ALL <- c(NA, 4, 5, 6)
score.c.ALL <- c(NA, NA, NA, 1)
dat <- data.frame(names, score.a.ALL, score.b.ALL, score.c.ALL)
dat$goal <- c(1, 3, 5, 3.3)
scoreALL <- dat[, grep("score\\.[^.]+\\.ALL", colnames(dat))]
dat$average <- rowSums(scoreALL, na.rm=T)/ ncol(scoreALL[,is.na==F])
The goal column is what the the average should be. Any help is much appreciated! Thanks!