Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Data frame row duplication in R

I currently have a data frame that looks like

Trial # Header Header 2 Header 3
1 1 1.1 1.2
2 2 2.1 2.2
3 3 3.1 3.2
4 4 4.1 4.2

And I need to add mutate the data frame so there is a year column and each trial repeats 3 times. Something that looks like:

Trial # Header Header 2 Header 3 Year
1 1 1.1 1.2 1
1 1 1.1 1.2 2
1 1 1.1 1.2 3
2 2 2.1 2.2 1
2 2 2.1 2.2 2
2 2 2.1 2.2 3
3 3 3.1 3.2 1
3 3 3.1 3.2 2
3 3 3.1 3.2 3
4 4 4.1 4.2 1
4 4 4.1 4.2 2
4 4 4.1 4.2 3

I am not sure how to go about accomplishing this so any help is appreciated!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

df %>%
  mutate(year = list(1:3))%>%
  unnest(year)

# A tibble: 12 x 5
   Trial Header Header.2 Header.3  year
   <int>  <int>    <dbl>    <dbl> <int>
 1     1      1      1.1      1.2     1
 2     1      1      1.1      1.2     2
 3     1      1      1.1      1.2     3
 4     2      2      2.1      2.2     1
 5     2      2      2.1      2.2     2
 6     2      2      2.1      2.2     3
 7     3      3      3.1      3.2     1
 8     3      3      3.1      3.2     2
 9     3      3      3.1      3.2     3
10     4      4      4.1      4.2     1
11     4      4      4.1      4.2     2
12     4      4      4.1      4.2     3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading