繁体   English   中英

我的 R function 在通过 map() 传递时接受单个列名但不接受列名列表

[英]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.

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