r - 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)
但是我没有想出在一张桌子上做这件事的方法。
解决方案
尝试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
推荐阅读
- android - 单选按钮在 radiobutton.setChecked(false) 之后取消选中自身
- algorithm - 按此向量中的映射成员对对象向量进行排序
- ubuntu - 如何检查您使用的是什么版本的 SilverStripe 插件?
- reactjs - 选择未出现的 React Component 数据选项
- javascript - Javascript Promises:当涉及到 javascript 远程调用时,你如何链接结果?
- c# - 错误语法 Sql Join in c# with sql server
- python - 从 .wav 文件中提取片段
- arrays - 将数据添加到数组 powershell
- sql - 仅显示库 SQL Rails 中的后续软件
- python - 熊猫丢弃行与过滤器