繁体   English   中英

将组添加到 R 中的 dataframe 中的行

[英]Adding groups to rows in a dataframe in R

我想从这个转换我的数据: current data.frame

对此:所需的data.frame

我不知道如何开始,欢迎任何帮助!

提前致谢,

米奇

一种使用reshape() melt()的解决方案

library(readr)
library(reshape)

 Data:

df<-structure(list(age_group = c("<20", ">70", "20-29", "30-39", 
"40-49", "50-59", "60-69"), no = c(19L, 1L, 447L, 196L, 92L, 
55L, 24L), yes = c(21L, 1L, 664L, 371L, 204L, 137L, 63L), total = c(2L, 
0L, 217L, 175L, 112L, 82L, 39L)), class = "data.frame", row.names = c(NA, 
-7L))

代码:

df<-melt(C0001)
df<-as.data.frame(df)
df[order(df$age_group),]

     age_group variable value
1        <20       no    19
8        <20      yes    21
15       <20    total     2
2        >70       no     1
9        >70      yes     1
16       >70    total     0
3      20-29       no   447
10     20-29      yes   664
17     20-29    total   217
4      30-39       no   196
11     30-39      yes   371
18     30-39    total   175
5      40-49       no    92
12     40-49      yes   204
19     40-49    total   112
6      50-59       no    55
13     50-59      yes   137
20     50-59    total    82
7      60-69       no    24
14     60-69      yes    63
21     60-69    total    39

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM