1

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

mmulder
  • 11
  • 1
  • 2
    Welcome to SO! Please don't upload code or data as images for [these reasons](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question/285557#285557). – Limey Dec 09 '21 at 11:34
  • 1
    Welcome to SO! Would you mind providing [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data, the code you tried and packages you used. Please do not post an image of code/data/errors [for these reasons](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question/285557#285557). – stefan Dec 09 '21 at 11:36
  • 1
    As above, but the function I would look into is `pivot_longer` from the `tidyr` package within the `tidyverse`. – Quixotic22 Dec 09 '21 at 11:38

1 Answers1

0

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
Rfanatic
  • 2,224
  • 1
  • 5
  • 21
  • @mmulder Glad the code worked for you. You must read and act upon this short post stackoverflow.com/help/someone-answers. – Rfanatic Dec 09 '21 at 12:07
  • The `reshape` package is extremely old. While it may work here, if you are trying to learn how to do these things, I would not advise this approach. The comment by Quixotic22 provides the actively maintained alternative which should be preferred (`tidyr::pivot_longer()`). –  Dec 09 '21 at 14:08