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

前端 未结 6 1734
一个人的身影
一个人的身影 2020-12-03 05:07

I want to add a suffix or prefix to most variable names in a data.frame, typically after they\'ve all been transformed in some way and before performing a join. I don\'t ha

6条回答
  •  忘掉有多难
    2020-12-03 05:43

    This is more of a step back, but you might think of reshaping your data in order to apply the function to multiple years at the same time. This will preserve tidyness. If you're going to want to end up comparing different years, it might make sense to have the year be a separate variable in a dataframe, rather than storing the year in the names. You should be able to use summarise_ to get the mean_year behavior. See http://cran.r-project.org/web/packages/dplyr/vignettes/nse.html

    library(dplyr)
    library(tidyr)
    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))
    
    dat14 %>% 
      gather(variable, value, -ID, -class) %>% 
      mutate(year = 2014) %>% 
      group_by(class, year, variable)%>% 
      summarise(mean = mean(value))`
    

提交回复
热议问题