简体   繁体   中英

passing data.frame column names to a function

I've seen similar posts that mention the need for use of quotes to pass column names to functions, but I could use help in what I have wrong and how I could improve the function. For example, maybe I could add a "suffix" argument to automatically assign the new data.frame with a suffixed name of the original? I'm hoping to be able to have a generic function that I could use for varying column names and positions. Thank you.

library(tidyverse)  

# function definition #
  createhrly_0595quants <- function(df, hourcolumn, 
     value, qtype, metadata_to_add)   {

df <- df  %>% group_by(hourcolumn) %>%
         summarize(`05%`=quantile(value, probs=0.05, type =qtype),
        `95%`=quantile(value, probs=0.95, type = qtype),
         median = median(value), n=n()) %>% 
         mutate(qtype = qtype, metadata_to_add = metadata_to_add)

}

# sample data.frame #
hrly_gmt  <- seq(from=as.POSIXct("2018-11-20 01:00", 
tz="America/Los_Angeles"), to=as.POSIXct("2018-11-20 23:00", 
 tz="America/Los_Angeles"), by="1 hours")  
myvalues1 <- rnorm(23)
myvalues2 <- rnorm(23)
mydf1 <- data.frame(hrly_gmt, myvalues1) %>% mutate(class = "a")
mydf2 <- data.frame(hrly_gmt, myvalues2) %>% mutate(class = "b")
df_x <- rbind(mydf1, mydf2)

# function use #
df_0595quants <- createhrly_0595quants(df_x, "hrly_gmt",
                 "myvalues", 4, "version x.2")

As we pass strings as input, instead of using group_by , we can use group_by_at which takes strings for column names, the summarize column can be converted to symbol ( sym ) and evaluate ( !! )

createhrly_0595quants <- function(df, hourcolumn, 
 value, qtype, metadata_to_add)   {

  value <- rlang::sym(value)


    df  %>% 
      group_by_at(vars(hourcolumn)) %>%
      summarize(`05%`=quantile(!!value, probs=0.05, type =qtype),
              `95%`=quantile(!!value, probs=0.95, type = qtype),
             median = median(!!value), n=n()) %>% 
     mutate(qtype = qtype, 
     metadata_to_add = metadata_to_add)
 }



createhrly_0595quants(df_x, "hrly_gmt",
                  "myvalues", 4, "version x.2")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM