我想使用 table
和 addmargins
创建一个交叉表,然后将另一个数据框中的列添加到表中。
示例数据:
df <- data.frame(country = c("B", "A", "C", "C", "A", "A", "B", "C", "C"), year = c(2005, 2006, 2005, 2007, 2005, 2005, 2007, 2006, 2006))
df2 <- data.frame(country = c("C", "B", "A", "C", "A", "B", "C", "A", "A", "A", "B", "C", "B", "A", "C"))
我想合并:
addmargins(table(df$country, df$year), FUN = list(Total = sum))
addmargins(table(df2$country), FUN = list(Total = sum))
这样我就得到了
2005 2006 2007 Total df2
A 2 1 0 3 6
B 1 0 1 2 4
C 1 2 1 4 5
Total 4 3 2 9 15
最佳答案
我们可以使用cbind:
cbind(
addmargins(table(df[ c("country", "year") ]), FUN = list(Total = sum), quiet = TRUE),
df2 = addmargins(table(df2[ "country"] ), FUN = list(Total = sum)))
# 2005 2006 2007 Total df2
# A 2 1 0 3 6
# B 1 0 1 2 4
# C 1 2 1 4 5
# Total 4 3 2 9 15
关于r - 将来自不同数据框的列添加到交叉表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72443295/