首页 > 解决方案 > R - 如何从 2 列中提取信息

问题描述

我有一个包含超过 2 000 000 条记录的数据框。这是示例数据:

year <- c(2002, 2002, 2001, 2001, 2000)
type<- c(“red”, “red”, “blue”, “blue”, “blue”)
mydata <- data.frame(year, type)

我需要每年提取类型,看起来像这样:

2002:
“red”: 2, “blue”: 0
2001:
“red”: 0, “blue”: 2
2000:
“red”: 0, “blue”: 1

我可以使用 table() 单独提取它:

table(mydata$year)
table(mydata$type)

但是我没有想出在一张桌子上做这件事的方法。

标签: rdataframe

解决方案


尝试aggregate如下

aggregate(type ~ ., mydata, function(x) table(factor(x, levels = unique(type))))

这使

  year type.red type.blue
1 2000        0         1
2 2001        0         2
3 2002        2         0

另一个基本 R 选项使用xtabs

xtabs(~ year + type, mydata)

      type
year   blue red
  2000    1   0
  2001    2   0
  2002    0   2

推荐阅读