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

How to duplicate a row in a dataframe and relocate it just after the original row?

let’s say I have this df

original_df <- data.frame(
  ID = c(1, 2, 3),
  Name = c("Alice", "Bob", "Charlie"),
  Age = c(25, 30, 22)
)

I wish the following output

  ID    Name Age
1  1   Alice  25
2  2     Bob  30
3  2     Bob  30
4  3 Charlie  22

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 :

You can repeat your row number in [:

original_df[c(1, 2, 2, 3), ]

To make it more flexible, you can use append to create a new sequence of row indices.

new_seq <- append(seq(nrow(original_df)), values = 2, after = 2)
original_df[new_seq, ]
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