dplyr - Adding prefix or suffix to most data.frame variable names in piped R workflow -


i want add suffix or prefix variable names in data.frame, typically after they've been transformed in way , before performing join. don't have way without breaking piping.

for example, data:

library(dplyr) set.seed(1) dat14 <- data.frame(id = 1:10, speed = runif(10), power = rpois(10, 1),                     force = rexp(10), class = rep(c("a", "b"),5)) 

i want result (note variable names):

  class speed_mean_2014 power_mean_2014 force_mean_2014 1           0.5572500             0.8       0.5519802 2     b       0.2850798             0.6       1.0888116 

my current approach is:

means14 <- dat14 %>%   group_by(class) %>%   select(-id) %>%   summarise_each(funs(mean(.)))    names(means14)[2:length(names(means14))] <- paste0(names(means14)[2:length(names(means14))], "_mean_2014") 

is there alternative clunky last line breaks pipes? i've looked @ select() , rename() don't want explicitly specify each variable name, want rename except single variable , might have wider data.frame in example.

i'm imagining final piped command approximates made-up function:

appendname(cols = 2:n, str = "_mean_2014", placement = "suffix") 

which doesn't exist far know.

after additional experimenting since posting question, i've found setnames function work piping returns data.frame:

dat14 %>%   group_by(class) %>%   select(-id) %>%   summarise_each(funs(mean(.))) %>%   setnames(c(names(.)[1], paste0(names(.)[-1],"_mean_2014")))     class speed_mean_2014 power_mean_2014 force_mean_2014 1           0.5572500             0.8       0.5519802 2     b       0.2850798             0.6       1.0888116 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -