r - subtract mean from every element dplyr -
i want demean columns using dplyr. tried failed using "do()" command.
i want replicate following using easier dplyr commands:
tickers <- c(rep(1,10),rep(2,10)) df <- data.frame(cbind(tickers,rep(1:20),rep(2:21))) colnames(df) <- c("tickers","col1","col2") df %>% group_by(tickers) apply(df[,2:3],2,function(x) x - mean(x))
i sure can done better using dplyr.
thanks!
if using dplyr
, can mutate_each
, use of methods mentioned in ?select
match columns. here, using matches
can take regular expression pattern.
library(dplyr) df %>% mutate_each(funs(.-mean(.)), matches('^col')) %>% select(-tickers)
but can done using base r
:
df[2:3]-colmeans(df[2:3])[col(df[2:3])]
the colmeans
output vector
can replicated lengths same.
Comments
Post a Comment