Compute the mean of two columns in a dataframe
We can use rowMeans
a$mean <- rowMeans(a[,c('high', 'low')], na.rm=TRUE)
NOTE: If there are NA values, it is better to use rowMeans
For example
a <- data.frame(High= c(NA, 3, 2), low= c(3, NA, 0))
rowMeans(a, na.rm=TRUE)
#[1] 3 3 1
and using +
a1 <- replace(a, is.na(a), 0)
(a1[1] + a1[2])/2
# High
#1 1.5
#2 1.5
#3 1.0
NOTE: This is no way trying to tarnish the other answer. It works in most cases and is fast as well.
For the mean of two numbers you don't really need any special functions:
a$mean = (a$high + a$low) / 2
For such an easy case, this avoids any conversions to matrix
to use apply
or rowMeans
.