在R中汇总/重塑数据

时间:2016-05-06 15:15:22

标签: r

对于示例数据框:

df <- structure(list(id = 1:18, region = structure(c(1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("a", 
"b"), class = "factor"), age.cat = structure(c(1L, 1L, 2L, 2L, 
2L, 3L, 3L, 4L, 1L, 1L, 1L, 1L, 2L, 2L, 3L, 4L, 4L, 4L), .Label = c("0-18", 
"19-35", "36-50", "50+"), class = "factor")), .Names = c("id", 
"region", "age.cat"), class = "data.frame", row.names = c(NA, 
-18L))

我想重塑数据,详情如下:

region 0-18 19-35 36-50 50+
a      2    3     2     1
b      4    2     1     3

我只是简单地聚合或重塑数据吗?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:6)

您只需使用table

即可
 table(df$region, df$age.cat)

    0-18 19-35 36-50 50+
  a    2     3     2   1
  b    4     2     1   3

答案 1 :(得分:2)

使用reshape2

install.packages('reshape2')
library(reshape2)

df1 <- melt(df, measure.vars = 'age.cat')
df1 <- dcast(df1, region ~ value)