使用计数将长格式转换为宽格式的简单方法 [英] Easy way to convert long to wide format with counts
本文介绍了使用计数将长格式转换为宽格式的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数据集:
sample.data <- data.frame(Step = c(1,2,3,4,1,2,1,2,3,1,1),
Case = c(1,1,1,1,2,2,3,3,3,4,5),
Decision = c("Referred","Referred","Referred","Approved","Referred","Declined","Referred","Referred","Declined","Approved","Declined"))
sample.data
Step Case Decision
1 1 1 Referred
2 2 1 Referred
3 3 1 Referred
4 4 1 Approved
5 1 2 Referred
6 2 2 Declined
7 1 3 Referred
8 2 3 Referred
9 3 3 Declined
10 1 4 Approved
11 1 5 Declined
在 R 中是否有可能将其转换为宽表格式,由标题决定,每个单元格的值是出现次数,例如:
Is it possible in R to translate this into a wide table format, with the decisions on the header, and the value of each cell being the count of the occurrence, for example:
Case Referred Approved Declined
1 3 1 0
2 1 0 1
3 2 0 1
4 0 1 0
5 0 0 1
推荐答案
您可以使用简单的 table()
语句完成此操作.您可以通过设置因子水平来获得您想要的响应.
You can accomplish this with a simple table()
statement. You can play with setting factor levels to get your responses the way you want.
sample.data$Decision <- factor(x = sample.data$Decision,
levels = c("Referred","Approved","Declined"))
table(Case = sample.data$Case,sample.data$Decision)
Case Referred Approved Declined
1 3 1 0
2 1 0 1
3 2 0 1
4 0 1 0
5 0 0 1
这篇关于使用计数将长格式转换为宽格式的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文