我有如下数据集:
dat = structure(list(C86_1981 = c("Outer London", "Buckinghamshire",
NA, "Ross and Cromarty", "Cornwall and Isles of Scilly", NA,
"Kirkcaldy", "Devon", "Kent", "Renfrew"), C96_1981 = c("Outer London",
"Buckinghamshire", NA, "Ross and Cromarty", "Not known/missing",
NA, "Kirkcaldy", NA, NA, NA), C00_1981 = c("Outer London", "Inner London",
"Lancashire", "Ross and Cromarty", NA, "Humberside", "Kirkcaldy",
NA, NA, NA), C04_1981 = c("Kent", NA, NA, "Ross and Cromarty",
NA, "Humberside", "Not known/missing", NA, NA, "Renfrew"), C08_1981 = c("Kent",
"Oxfordshire", NA, "Ross and Cromarty", "Cornwall and Isles of Scilly",
"Humberside", "Dunfermline", NA, NA, "Renfrew"), C12_1981 = c("Kent",
NA, NA, "Ross and Cromarty", "Cornwall and Isles of Scilly",
"Humberside", "Dunfermline", NA, NA, "Renfrew")), row.names = c(NA,
-10L), class = c("tbl_df", "tbl", "data.frame"), .Names = c("C86_1981",
"C96_1981", "C00_1981", "C04_1981", "C08_1981", "C12_1981"))
我想对每一列使用
dplyr::count()
。期望输出:# A tibble: 10 x 3
C86_1981 dat86_n dat96_n ...
<chr> <int> <int>
1 Buckinghamshire 1 1
2 Cornwall and Isles of Scilly 1 NA
3 Devon 1 NA
4 Kent 1 NA
5 Kirkcaldy 1 1
6 Outer London 1 1
7 Renfrew 1 NA
8 Ross and Cromarty 1 1
9 <NA> 2 5
10 Not known/missing NA 1
目前我正在手动完成这个任务,然后使用dplyr::full_join()
来合并结果:
library("tidyverse")
dat86_n = dat %>%
count(C86_1981) %>%
rename(dat86_n = n)
dat96_n = dat %>%
count(C96_1981) %>%
rename(dat96_n = n)
# ...
dat_counts = dat86_n %>%
full_join(dat96_n, by = c("C86_1981" = "C96_1981"))
# ...
这个方法可以实现功能,但如果我的数据稍后有任何更改,它就不够健壮。我希望能以编程方式解决这个问题。
我尝试了一个循环:
lapply(dat, count)
# Error in UseMethod("groups") :
# no applicable method for 'groups' applied to an object of class "character"
(purrr::map()
也会出现相同的错误)。我认为这个错误是因为 count()
函数期望接收一个tbl
和一个单独的变量作为参数,所以我也尝试了这种方式:
lapply(dat, function(x) {
count(dat, x)
})
# Error in grouped_df_impl(data, unname(vars), drop) :
# Column `x` is unknown
再次运行purrr::map()
时出现相同的错误。我也尝试了summarise_all()
的变体:
dat %>%
summarise_all(count)
# Error in summarise_impl(.data, dots) :
# Evaluation error: no applicable method for 'groups' applied to an object of class "character".
我感觉我错过了一些显而易见的东西,解决方案应该很简单。dplyr
的解决方案特别受欢迎,因为这是我经常使用的。
ungroup()
,因为count()
已经帮你做了这个,但除此之外完美无缺。 - Phil