[英]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? 例如,也许我可以添加“后缀”参数以自动为新的data.frame
分配带有原始后缀的名称? 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 ( !!
) 当我们将字符串作为输入传递时,而不是使用group_by
,我们可以使用group_by_at
,它使用字符串作为列名, summarize
列可以转换为符号( sym
)并求值( !!
)
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.