簡體   English   中英

將tabyl函數應用於R中的多列

[英]Applying tabyl function to multiple columns in R

我有一個類似於以下內容的數據框:

x1 <- as.factor(c('Yes', 'Yes', 'No', NA, 'Yes', 'Yes', 'Yes')) 
x2 <- as.factor(c('Yes', NA, 'No', 'No', 'No', 'No', 'Yes'))
x3 <- as.factor(c('Yes', 'No', 'No', 'No', 'No', 'No', 'No'))
y <- as.factor(c('Male', 'Male', 'Female', 'Other', 'Female', 'Female', 'Male'))
df <- data.frame(x1, x2, x3, y)

我為tabyl編寫了一個函數,如下所示......

tabulate <- function(df,x) {
  output <- df %>% 
    tabyl(!! rlang::sym(x), y, show_missing_levels = FALSE, show_na = FALSE) %>%
    adorn_totals(where = "row") %>% 
    adorn_percentages(denominator = "col") %>% 
    adorn_pct_formatting() %>%
    adorn_ns(position = "front")
  return(output)
}

...我現在想將它應用到我的數據框中的所有“x”列,如下所示:

tabulate(df, 'x1')
tabulate(df, 'x2')
tabulate(df, 'x3')

我的問題:如何使用循環/迭代命令,這樣我就不必運行該函數 3 次(x1、x2 和 x3 各一次),並且還理想地保持我從原始版本獲得的布局/標簽tabyl輸出? (例如,我知道lapply ,但鑒於它返回列表,我不確定如何在這里有效地使用它)。

我們遍歷以“x”開頭的列名並應用函數

nm1 <- names(df)[startsWith(names(df), "x")]
lapply(nm1, tabulate, df = df)

-輸出

[[1]]
    x1     Female       Male
    No 1  (33.3%) 0   (0.0%)
   Yes 2  (66.7%) 3 (100.0%)
 Total 3 (100.0%) 3 (100.0%)

[[2]]
    x2     Female       Male      Other
    No 3 (100.0%) 0   (0.0%) 1 (100.0%)
   Yes 0   (0.0%) 2 (100.0%) 0   (0.0%)
 Total 3 (100.0%) 2 (100.0%) 1 (100.0%)

[[3]]
    x3     Female       Male      Other
    No 3 (100.0%) 2  (66.7%) 1 (100.0%)
   Yes 0   (0.0%) 1  (33.3%) 0   (0.0%)
 Total 3 (100.0%) 3 (100.0%) 1 (100.0%)

或者使用map

purrr::map(nm1, tabulate, df = df)

或者,也可以使用acrosssummarise並存儲為一個list

library(dplyr)
out <- df %>%
     summarise(across(starts_with('x'), 
          ~ list(tabulate(df = cur_data(), cur_column())))) 

然后,我們可以unclass

unclass(out)

暫無
暫無

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

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