[英]How to set levels of a factor to be columns in R?
Here I have a table我这里有一张桌子
tab <- matrix(c('AL', 'Accident', 14, 19, 'AR', 'Accident', 17, 6, 'AL', 'Disease', 14, 19, 'AR', 'Disease', 17, 6), ncol=4, byrow=TRUE)
colnames(tab) <- c('State','Cause','under30', 'above30')
rownames(tab) <- c(1,2,3,4)
tab <- as.table(tab)
tab
which looks like看起来像
I want to make it to be我想让它成为
But I don't know how to do it, is there any hint or help?但我不知道该怎么做,有什么提示或帮助吗? Thanks in advance.
提前致谢。 (This is only a simplified version of my dataset, the actual dataset is much bigger. What I am looking for is a generalized method.)
(这只是我的数据集的简化版本,实际数据集要大得多。我正在寻找的是一种通用方法。)
Consider converting to data.frame
and then use pivot_wider
考虑转换为
data.frame
然后使用pivot_wider
library(tidyr)
pivot_wider(as.data.frame.matrix(tab), names_from = Cause,
values_from = c(under30, above30), names_glue = "{Cause}_{.value}")
-output -输出
# A tibble: 2 × 5
State Accident_under30 Disease_under30 Accident_above30 Disease_above30
<chr> <chr> <chr> <chr> <chr>
1 AL 14 14 19 19
2 AR 17 17 6 6
In base R:在基地 R 中:
reshape(as.data.frame.matrix(tab),
dir='wide', idvar = 'State', timevar = 'Cause', sep='_')
State under30_Accident above30_Accident under30_Disease above30_Disease
1 AL 14 19 14 19
2 AR 17 6 17 6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.