我正在尝试重新排列数据以汇总为特定格式。
要汇总和重新排列的数据:
type user
phone A
phone B
email A
email A
phone B
phone A
所需格式:
type A B
phone 2 2
email 2 0
答案 0 :(得分:0)
我们用count
和spread
的频率从“长”到“宽”
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))