代码之家  ›  专栏  ›  技术社区  ›  piptoma

具有数据帧和变量参数的Lappy函数

  •  1
  • piptoma  · 技术社区  · 7 年前

    我简化了功能 为了说明我的问题,即它比下面显示的更复杂。注意,函数的一般结构应该保持不变:它使用一个参数来指定要处理的数据帧( df ),以及要总结的变量的参数( variable_to_test

    my_fun <- function(df, variable_to_test) {
    
      variable_to_test <- enquo(variable_to_test)
      new_var_name <- paste0(quo_name(variable_to_test), "_new_name")
    
      df %>% 
        summarise(
          !!new_var_name := sum(!!variable_to_test, na.rm = TRUE)
        ) 
    }
    

    举个例子,我可以在数据帧中的每个变量上应用该函数:

    library(tidyverse)
    dat <- tibble(
      variable_1 = c(1:5, NA, NA, NA, NA, NA),
      variable_2 = c(NA, NA, NA, NA, NA, 11:15)
    )
    
    
    > my_fun(dat, variable_1)
    # A tibble: 1 x 1
       variable_1_new_name
                     <int>
    1                  15
    
    
    > my_fun(dat, variable_2)
    # A tibble: 1 x 1
      variable_2_new_name
                    <int>
    1                  65
    

    > dat %>%
    + lapply(., my_fun)
    Error in duplicate(quo) : argument "quo" is missing, with no default
    Called from: duplicate(quo)
    

    lapply() 功能?

    2 回复  |  直到 7 年前
        1
  •  2
  •   piptoma    7 年前

    哦,我认为你只是在错误的事情上映射。对于tidyverse解决方案,我会尝试:

    map(dat, ~my_fun(dat, .))
    

    .

        2
  •  1
  •   Lionel Henry    7 年前

    你工作水平不对。如果将函数映射到数据帧上,则此函数应采用 my_fun()

    你需要找到其他解决问题的方法。一种解决方案是使用dplyr提供的映射器:

    dat %>%
      summarise_all(sum, na.rm = TRUE) %>%
      rename_all(paste0, "_new_name")
    

    您可以等效地使用 map() set_names() 来自purrr。

    dat %>%
      map_df(sum, na.rm = TRUE) %>%
      set_names(paste0, "_new_name")