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

如何使用r中的map/apply函数族对所有变量应用count()?

  •  1
  • ViSa  · 技术社区  · 5 年前

    我试图创建一个用户定义的函数来显示数据帧中每个变量的频率计数。

    dummy_df <- data.frame(gender_vector = c("Male", "Female", "Female", "Male", "Male"),
                              color_vector = c('blue', 'red', 'green', 'white', 'black')
    ) 
    
    dummy_df
    
      gender_vector color_vector
    1          Male         blue
    2        Female          red
    3        Female        green
    4          Male        white
    5          Male        black
    

    单变量运行计数:

    dummy_df %>%
        count(gender_vector) %>%
        as.tibble() %>% 
        
        ggplot(aes(x = n, y = gender_vector, fill = gender_vector)) +
        geom_col(show.legend = FALSE)
    

    enter image description here

    问题:

    var_freq_plot_fn <- function(df, selected_var){
      df %>% 
        select_if(is.character) %>%
        count(selected_var) %>%
        as.tibble() %>% 
        
        ggplot(aes(x = n, y = selected_var, fill = selected_var)) +
        geom_col() +
        theme(legend.position = "none")
    }
    
    map(dummy_df, var_freq_plot_fn)
    

    错误: Error in UseMethod("tbl_vars") : no applicable method for 'tbl_vars' applied to an object of class "character" .

    我想通过使用 tibble 而不是 dataframe 但我错了。

    我还是不清楚为什么会这样 r datatypes 当事物被放入 function .

    1 回复  |  直到 5 年前
        1
  •  0
  •   Ronak Shah    5 年前

    当它们在函数中时,情况就不同了,特别是当你用名称而不是值来引用它们时。尝试:

    library(dplyr)
    library(ggplot2)
    
    var_freq_plot_fn <- function(df, selected_var){
      df %>% 
        count(.data[[selected_var]]) %>%
        ggplot(aes(x = n, y = .data[[selected_var]], fill = .data[[selected_var]])) +
        geom_col() +
        theme(legend.position = "none")
    }
    
    plot_list <- purrr::map(names(dummy_df), var_freq_plot_fn, df = dummy_df)
    

    var_freq_plot_fn <- function(df){
      purrr::map(df %>% select_if(is.character) %>% names, ~
      df %>% 
        count(.data[[.x]]) %>%
        ggplot(aes(x = n, y = .data[[.x]], fill = .data[[.x]])) +
        geom_col() +
        theme(legend.position = "none"))
    }
    
    var_freq_plot_fn(dummy_df)
    
    推荐文章