通过变量计数汇总数据

时间:2018-12-27 06:18:28

标签: r dataframe

我正在尝试重新排列数据以汇总为特定格式。

要汇总和重新排列的数据:

type    user
phone   A
phone   B
email   A
email   A
phone   B
phone   A

所需格式:

type    A   B
phone   2   2
email   2   0

1 个答案:

答案 0 :(得分:0)

我们用countspread的频率从“长”到“宽”

library(tidyverse)
count(df1, type, user) %>%
   spread(user, n, fill = 0)
# A tibble: 2 x 3
#  type      A     B
#  <chr> <dbl> <dbl>
#1 email     2     0
#2 phone     2     2

或使用table中的base R

table(df1)

数据

df1 <- structure(list(type = c("phone", "phone", "email", "email", "phone", 
 "phone"), user = c("A", "B", "A", "A", "B", "A")), 
 class = "data.frame", row.names = c(NA, -6L))