Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat rows with specific value

Tags:

r

dplyr

I would like to repeat rows contain specific values in R with df as below

df <- data.frame(name1 = c("x","y","z"),
                 name2 = c(0,1,2))
df

  name1 name2
1     x     0
2     y     1
3     z     2

My desired output

  name1 name2
1     x     0
2     x     0
3     y     1
4     y     1
5     z     2

I would like to say only rows containing 'x' and 'y' will be repeated one time. So far, I only came up with the idea of using add_row and replace NA values by the corresponding values. Any sugesstions for this using tidyverse?

like image 631
Anh Avatar asked Oct 29 '25 18:10

Anh


1 Answers

We could do it this way:

library(dplyr)
df %>% 
  filter(name1=="x" | name1=="y") %>% 
  bind_rows(df) %>% 
  arrange(name1)

  name1 name2
1     x     0
2     x     0
3     y     1
4     y     1
5     z     2
like image 71
TarJae Avatar answered Oct 31 '25 08:10

TarJae