我有以下数据框
tbl <- structure(list(col1 = c("a", NA, "b", NA, "c", "c"), col2 = c("n",
"n", "b", "a", NA, "c"), col3 = c("z", "a", "z", "b", "1", "c"
)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"
))
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)# A tibble: 6 x 3 col1 col2 col3 <chr> <chr> <chr> 1 a n z 2 NA n a 3 b b z 4 NA a b 5 c NA 1 6 c c c
是否可以将 dplyr::count 函数应用于每一列或返回每列的唯一条目以及可能每个唯一值出现的数量的其他函数?
我们可以循环nameswithmap并应用count
library(dplyr)
library(purrr)
map(names(tbl), ~ tbl %>%
select(.x) %>%
count(!! rlang::sym(.x)))
Run Code Online (Sandbox Code Playgroud)
或者可以申请table并summarise_all返回一list列
tbl %>%
summarise_all( ~ list(table(.)))
Run Code Online (Sandbox Code Playgroud)
或者对于不同元素的数量
tbl %>%
summarise_all(n_distinct)
Run Code Online (Sandbox Code Playgroud)
或者在base R
lapply(tbl, function(x) as.data.frame(table(x)))
Run Code Online (Sandbox Code Playgroud)