正在使用 RShiny 應用程式,目前在使用dplyr'sgroup_by()功能時遇到問題。我有兩個定義的功能:
gather_info:找到具有最高/最低平均值的類別paste_info:呼叫gather_info并回傳對應的類別和值
目的是回傳一個字串 - 給定一個資料框和分類變數 - 說明性能最高和最低的類別以及所述類別的值。
使用適當的引數呼叫gather_info按預期作業。但是,paste_info始終如一地回傳:
Error in `group_by()`:
! Must group by variables found in `.data`.
? Column `grp.col` is not found.
這是一個可重復的示例,其中所需的輸出paste_info是“根據您的資料,您表現最好的組是 Cat1 得分 90%,而您表現最差的組是 Cat2 得分 20%。” :
gather_info <- function(df, grp.col, maxm) {
df |>
mutate_if(
.predicate = function(x) is.character(x),
.funs = function(x) str_to_title(x)
) |>
group_by({{ grp.col }}) |>
summarize(percentage = round(mean(value, na.rm=TRUE) * 100, 2)) |>
arrange(desc(percentage)) %>% # c'est un pipe
{if (maxm) head(., 1) else tail(., 1)}
}
paste_info <- function(df, grp.col) {
high_df <- gather_info(df, grp.col, maxm=TRUE)
low_df <- gather_info(df, grp.col, maxm=FALSE)
paste0("Given your data, your best performing group is ",
high_df |> pull(grp.col), " scoring ", high_df$percentage, "%",
" and your worst performing group is ",
low_df |> pull(grp.col), " scoring ", low_df$percentage, "%.")
}
df <- data.frame(
category=c('cat1', 'cat1', 'cat2', 'cat2', 'cat2', 'cat3', 'cat3'),
value=c(1,0.8,0.2,0.3,0.1,0.5,0.5)
)
# returns category, value with highest mean value
gather_info(df, category, maxm=TRUE)
# returns category, value with lowest mean value
gather_info(df, category, maxm=FALSE)
# does not work
paste_info(df, category)
任何幫助深表感謝。謝謝!
uj5u.com熱心網友回復:
您必須使用{{inpaste_info來傳遞grp.coltogather_info以及 in pull:
library(dplyr)
paste_info <- function(df, grp.col) {
high_df <- gather_info(df, {{ grp.col }}, maxm = TRUE)
low_df <- gather_info(df, {{ grp.col }}, maxm = FALSE)
paste0(
"Given your data, your best performing group is ",
high_df |> pull({{ grp.col }}), " scoring ", high_df$percentage, "%",
" and your worst performing group is ",
low_df |> pull({{ grp.col }}), " scoring ", low_df$percentage, "%."
)
}
paste_info(df, category)
#> [1] "Given your data, your best performing group is Cat1 scoring 90% and your worst performing group is Cat2 scoring 20%."
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/526985.html
