tags:

views:

105

answers:

2

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]])
+2  A: 

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!

csgillespie
This gives wrong results. Subtraction from matrix works by columns no by rows.
Marek
+4  A: 

Alternative

accel[2:4] <- lapply(accel[2:4], function(x) x-weighted.mean(x))
Marek