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

Add a blank row after each unique value of a column in a dataframe in R

I was wondering if it might be possible to add one blank row after each unique value of study in my data below?

My Desired_output is below.

Please note that this is a toy data. A functional answer is highly 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

data <- data.frame(study=c(rep(1,2),2:3), year=c(rep(2001,2),2002:2003))

Desired_output =
" study year
1     1 2001
2     1 2001
             # <- Blank row
3     2 2002
             # <- Blank row
4     3 2003"

>Solution :

You can use group_split to split your data by group into a list of data frames. Then map a function over each list element and stack their output back into a data frame using map_dfr.

library(dplyr)
library(tibble)
library(purrr)

data %>% 
  group_split(study) %>% 
  map_dfr(~ add_row(.x, .after = Inf))

Output

  study  year
  <dbl> <dbl>
1     1  2001
2     1  2001
3    NA    NA
4     2  2002
5    NA    NA
6     3  2003
7    NA    NA
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