簡體   English   中英

如何使用 r 中的映射/應用函數系列對所有變量應用 count()?

[英]How to apply count() on all variables using a map/apply functions family in r?

我正在嘗試創建一個用戶定義的 function 來顯示 dataframe 的每個變量中的頻率計數。

df

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)

在此處輸入圖像描述

問題:但是當我使用它創建 function 時,它會產生一個問題:

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時會產生問題。

當它們在 function 中時情況有所不同,尤其是當您按名稱而不是按值引用它們時。 嘗試:

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)

function的另一種寫法:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM