简体   繁体   中英

Adding groups to rows in a dataframe in R

I want to transform my data from this: current data.frame

to this: desired data.frame

I have no clue how to start, any help is welcome!

Thanks in advance,

Mitch

One solution with 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))

Code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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