Rename column name using header / data frame name

I have a data frame called "Something." I am doing aggregation in one of the numeric columns using a generalization, and I want the name of this column to contain “Something” - the name of the data frame in the column name.

Example:

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

But I would call the aggregate column "avg_Something_score". Did that make sense?

+4
source share
5 answers

It seems like it makes sense to generate a new column name dynamically, so you don't need to hardcode the data frame name inside setNames. Perhaps something like a function below that takes a data frame, a grouping variable, and a numeric variable:

library(dplyr)
library(lazyeval)

my_fnc = function(data, group, value) {

  df.name = deparse(substitute(data))

  data %>%
    group_by_(group) %>%
    summarise_(avg = interp(~mean(v), v=as.name(value))) %>%
    rename_(.dots = setNames("avg", paste0("avg_", df.name, "_", value)))
}

:

my_fnc(mtcars, "cyl", "mpg")
    cyl avg_mtcars_mpg
  <dbl>          <dbl>
1     4       26.66364
2     6       19.74286
3     8       15.10000
my_fnc(iris, "Species", "Petal.Width")
     Species avg_iris_Petal.Width
1     setosa                0.246
2 versicolor                1.326
3  virginica                2.026
+2

rename_ dplyr deparse(substitute(Something)) :

Something %>%
group_by(Month) %>%
summarise(avg_score=mean(score))%>%
rename_(.dots = setNames("avg_score", 
 paste0("avg_",deparse(substitute(Something)),"_score") ))
+3

devel dplyr ( 0.6.0), quosure s

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

enquo , substitute from base R quosure, quo_name, , quosure unquoting (!! UQ) group_by/summarise/mutate .. lhs (:=) unquoting

+3
library(dplyr)

# Take mtcars as an example
# Calculate the mean of mpg using cyl as group
data(mtcars)
Something <- mtcars

# Create a list of expression
dots <- list(~mean(mpg))

# Apply the function, Use setNames to name the column
temp <- Something %>% 
  group_by(cyl) %>% 
  summarise_(.dots =  setNames(dots, 
                               paste0("avg_", as.character(quote(Something)), "_score")))
+2

You can use colnames (Something) <-c ("score", "something_avg_score")

0
source

Source: https://habr.com/ru/post/1675362/


All Articles