我有一个数据帧,看起来像这样:
Year Var Count
2019 A 10
2020 B 23
2019 B 36
2020 A 42如何使用"Count“列作为频率来制作年份x变量联想表?
发布于 2021-05-06 08:21:38
我们可以在base R中使用xtabs
xtabs(Count ~ Year + Var, df1)
# Var
#Year A B
# 2019 10 36
# 2020 42 23要包括行/列合计,可以使用addmargins
addmargins(xtabs(Count ~ Year + Var, df1))
# Var
#Year A B Sum
# 2019 10 36 46
# 2020 42 23 65
# Sum 52 59 111数据
df1 <- structure(list(Year = c(2019L, 2020L, 2019L, 2020L), Var = c("A",
"B", "B", "A"), Count = c(10L, 23L, 36L, 42L)), class = "data.frame",
row.names = c(NA,
-4L))发布于 2021-05-06 11:16:06
在janitor的帮助下,您可以在tidyverse中执行以下操作:
library(tidyr)
library(janitor)
df %>%
pivot_wider(names_from = Var, values_from = Count) %>%
adorn_totals(where = c("row", "col"))
# Year A B Total
# 2019 10 36 46
# 2020 42 23 65
# Total 52 59 111发布于 2021-05-06 15:25:57
使用reshape使其“宽”的基础R选项,即,
reshape(
df,
direction = "wide",
idvar = "Year",
timevar = "Var"
)给出
Year Count.A Count.B
1 2019 10 36
2 2020 42 23https://stackoverflow.com/questions/67410341
复制相似问题