Convert R-code to R-style

Is there a way to write the following statement more efficiently? acceleration is a data frame.

accel[[2]]<- accel[[2]]-weighted.mean(accel[[2]])
accel[[3]]<- accel[[3]]-weighted.mean(accel[[3]])
accel[[4]]<- accel[[4]]-weighted.mean(accel[[4]])
+3
source share
2 answers

Alternative

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

This is one way to do this.

accel[,2:4] = t(t(accel[,2:4]) - apply(accel[,2:4], 2, weighted.mean))

The following Marek spot has been fixed - thanks.

Moral: Always check your R-code before publishing!

+2
source

Source: https://habr.com/ru/post/1751283/


All Articles