Home > Mobile >  How to change grouped data in ungrouped data
How to change grouped data in ungrouped data

Time:12-09

I have grouped data that I want to convert to ungrouped data.

year<-c(rep(2014,4),rep(2015,4))
Age<-rep(c(22,23,24,25),2)
n<-c(1,1,3,2,0,2,3,1)
mydata<-data.frame(year,Age,n)

I would like to have a dataset like the one below created from the previous one.

   year Age
1  2014  22
2  2014  23
3  2014  24
4  2014  24
5  2014  24
6  2014  25
7  2014  25
8  2015  23
9  2015  23
10 2015  24
11 2015  24
12 2015  24
13 2015  25

CodePudding user response:

Try

mydata[rep(1:nrow(mydata),mydata$n),]

    year Age n
1   2014  22 1
2   2014  23 1
3   2014  24 3
3.1 2014  24 3
3.2 2014  24 3
4   2014  25 2
4.1 2014  25 2
6   2015  23 2
6.1 2015  23 2
7   2015  24 3
7.1 2015  24 3
7.2 2015  24 3
8   2015  25 1

CodePudding user response:

You can also use tidyr syntax for this:

library(tidyr)

year<-c(rep(2014,4),rep(2015,4))
Age<-rep(c(22,23,24,25),2)
n<-c(1,1,3,2,0,2,3,1)
mydata<-data.frame(year,Age,n)

uncount(mydata, n)
#>    year Age
#> 1  2014  22
#> 2  2014  23
#> 3  2014  24
#> 4  2014  24
#> 5  2014  24
#> 6  2014  25
#> 7  2014  25
#> 8  2015  23
#> 9  2015  23
#> 10 2015  24
#> 11 2015  24
#> 12 2015  24
#> 13 2015  25

But of course you shouldn't use tidyr just because it is tidyr :) An alternate view of the Tidyverse "dialect" of the R language, and its promotion by RStudio.

CodePudding user response:

Here's a tidyverse solution:

library(tidyverse)
mydata %>%
  uncount(n)

which gives:

   year Age
1  2014  22
2  2014  23
3  2014  24
4  2014  24
5  2014  24
6  2014  25
7  2014  25
8  2015  23
9  2015  23
10 2015  24
11 2015  24
12 2015  24
13 2015  25

CodePudding user response:

We can use tidyr::complete

library(tidyr)
library(dplyr)

mydata %>% group_by(year, Age) %>%
    complete(n = seq_len(n)) %>%
    select(-n) %>%
    ungroup()

# A tibble: 14 × 2
    year   Age
   <dbl> <dbl>
 1  2014    22
 2  2014    23
 3  2014    24
 4  2014    24
 5  2014    24
 6  2014    25
 7  2014    25
 8  2015    23
 9  2015    23
10  2015    24
11  2015    24
12  2015    24
13  2015    25
14  2015    22
  • Related