Is there a way to write the following statement more effectively? accel is a dataframe.
accel[[2]]<- accel[[2]]-weighted.mean(accel[[2]])
accel[[3]]<- accel[[3]]-weighted.mean(accel[[3]])
accel[[4]]<- accel[[4]]-weighted.mean(accel[[4]])
Is there a way to write the following statement more effectively? accel is a dataframe.
accel[[2]]<- accel[[2]]-weighted.mean(accel[[2]])
accel[[3]]<- accel[[3]]-weighted.mean(accel[[3]])
accel[[4]]<- accel[[4]]-weighted.mean(accel[[4]])
This is one way of doing it.
accel[,2:4] = t(t(accel[,2:4]) - apply(accel[,2:4], 2, weighted.mean))
Corrected following Marek spot - thanks.
Morale: Always check your R code before posting!
Alternative
accel[2:4] <- lapply(accel[2:4], function(x) x-weighted.mean(x))