@ Henrik的是易用性更好,因为这会令列字符,不再数字匹配,但你问什么...
mtcars %>%
group_by (am, gear) %>%
summarise (n=n()) %>%
mutate(rel.freq = paste0(round(100 * n/sum(n), 0), "%"))
## am gear n rel.freq
## 1 0 3 15 79%
## 2 0 4 4 21%
## 3 1 4 8 62%
## 4 1 5 5 38%
编辑因为Spacedman问它:-)
as.rel_freq <- function(x, rel_freq_col = "rel.freq", ...) {
class(x) <- c("rel_freq", class(x))
attributes(x)[["rel_freq_col"]] <- rel_freq_col
x
}
print.rel_freq <- function(x, ...) {
freq_col <- attributes(x)[["rel_freq_col"]]
x[[freq_col]] <- paste0(round(100 * x[[freq_col]], 0), "%")
class(x) <- class(x)[!class(x)%in% "rel_freq"]
print(x)
}
mtcars %>%
group_by (am, gear) %>%
summarise (n=n()) %>%
mutate(rel.freq = n/sum(n)) %>%
as.rel_freq()
## Source: local data frame [4 x 4]
## Groups: am
##
## am gear n rel.freq
## 1 0 3 15 79%
## 2 0 4 4 21%
## 3 1 4 8 62%
## 4 1 5 5 38%
这些百分比是你想要的实际数量吗?它们来自哪里,代数?啊,79%是15 /(15 + 4),21%是4 /(15 + 4),然后对于== == 1 62%是8 /(8 + 5)等等。 – Spacedman
@Spacedman是的,这些是我想要的数字,弗兰克是正确的,他们通过am变量(79 + 21)和(62 + 38)总和为100%。 – jenswirf
这真的好像是在寻找一个本地的dplyr实现''prop.table()'/'sweep()'。此外,在其他问题中,有些人[要求为变量或变量交互包含零计数](http://stackoverflow.com/questions/23778195/using-dplyr-for-frequency-counts-of- – smci