Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming a column name, by using the data frame title/name

Tags:

r

dplyr

I have a data frame called "Something". I am doing an aggregation on one of the numeric columns using summarise, and I want the name of that column to contain "Something" - data frame title in the column name.

Example:

    temp <- Something %>% 
    group_by(Month) %>% 
    summarise(avg_score=mean(score))

But i would like to name the aggregate column as "avg_Something_score". Did that make sense?

like image 340
Tushar Singh Avatar asked Apr 21 '17 15:04

Tushar Singh


2 Answers

We can use the devel version of dplyr (soon to be released 0.6.0) that does this with quosures

library(dplyr)
myFun <- function(data, group, value){
      dataN <- quo_name(enquo(data))
      group <- enquo(group)
      value <- enquo(value)

      newName <- paste0("avg_", dataN, "_", quo_name(value))
     data %>%
        group_by(!!group) %>%
        summarise(!!newName := mean(!!value))
 }

myFun(mtcars, cyl, mpg)
# A tibble: 3 × 2
#   cyl avg_mtcars_mpg
#  <dbl>          <dbl>
#1     4       26.66364
#2     6       19.74286
#3     8       15.10000

myFun(iris, Species, Petal.Width)
# A tibble: 3 × 2
#     Species avg_iris_Petal.Width
#     <fctr>                <dbl>
#1     setosa                0.246
#2 versicolor                1.326
#3  virginica                2.026

Here, the enquo takes the input arguments like substitute from base R and converts to quosure, with quo_name, we can convert it to string, evaluate the quosure by unquoting (!! or UQ) inside group_by/summarise/mutate etc. The column names on the lhs of assignment (:=) can also evaluated by unquoting to get the columns of interest

like image 73
akrun Avatar answered Oct 05 '22 13:10

akrun


You can use rename_ from dplyr with deparse(substitute(Something)) like this:

Something %>%
group_by(Month) %>%
summarise(avg_score=mean(score))%>%
rename_(.dots = setNames("avg_score", 
 paste0("avg_",deparse(substitute(Something)),"_score") ))
like image 34
Pierre Lapointe Avatar answered Oct 05 '22 14:10

Pierre Lapointe