Christian
Christian

Reputation: 26437

Transforming R code into R style

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]])

Upvotes: 3

Views: 199

Answers (2)

csgillespie
csgillespie

Reputation: 60522

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!

Upvotes: 2

Marek
Marek

Reputation: 50783

Alternative

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

Upvotes: 4

Related Questions