[英]My R function accepts individual column names but not lists of column names when passed through map()
使用此論壇數月后,我終於對社區提出了一個問題,我似乎無法在其他地方找到充分解決的問題。
在 R 中,我創建了一個 function,它在通過 map() 時接受單個列名但不接受列名列表。 問題似乎是評估之一,所以嘗試了 quo() 和 enquo(),但由於我沒有正確理解它們是如何工作的,所以我需要一些幫助。
我嘗試遍歷 function 的不同版本(根據錯誤消息注釋掉有問題的行)但這只會解決問題而不會解決它。 提前致謝。
# Load:
library(tidyverse)
# Create df:
set.seed(12)
df <- tibble(col1 = sample(c("a", "b", "c"), 10, replace = TRUE),
col2 = sample(1:4, 10, replace = TRUE),
col3 = sample(1:4, 10, replace = TRUE))
# My function:
my_function <- function(col_name) {
df <- df %>%
filter({{ col_name }} != 1) %>%
group_by(fct_relevel(factor(col1), "c", "b", "a")) %>%
mutate(col4 = 5 - {{ col_name }}) %>%
summarise("Score" = mean(col4)) %>%
rename("Levels" =
`fct_relevel(factor(col1), "c", "b", "a")`)
return(df)
}
# List of col_names to pass to function:
col_list <- list(df$col2, df$col3)
# Attempt function in map() using list of col_names:
map(col_list, my_function)
# Gives error message:
# Error in `mutate()`:
# ! Problem while computing `col4 = 5 - c(1L, 2L, 1L, 2L,
# 4L, 2L, 2L, 3L, 4L, 1L)`.
# ✖ `col4` must be size 2 or 1, not 10.
# ℹ The error occurred in group 1: fct_relevel(factor(col1), "c",
# "b", "a") = c.
您遇到的一個問題是col_list
實際上不是列名列表,而是來自這些列的實際數據。
我不完全確定你希望得到什么 output,但我猜這是應用於每一列的my_function
結果的full_join
。 一種方法是:
new_f <- function(...){
df %>%
mutate(across(-col1, ~if_else(.x == 1L, NA, .x))) %>%
group_by("Levels" = fct_relevel(factor(col1), "c", "b", "a")) %>%
select(Levels, ...) %>%
summarize(across(everything(), ~ mean(5- .x, na.rm = TRUE)))
}
new_f(col2, col3)
new_f(col2)
new_f(col3)
現在,我意識到,也許我錯過了你的真實意圖。 例如,也許您正在嘗試了解如何使用purrr::map
。 如果是這樣,請發表評論或更新您的問題。
無論如何,您應該查看Programming with dplyr
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.