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
?
CodePudding user response:
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
CodePudding user response:
You can create a new column specifying number of times a row should be repeated and then use uncount
to repeat them.
library(dplyr)
library(tidyr)
df %>%
mutate(repeat_row = ifelse(name1 %in% c('x', 'y'), 2, 1)) %>%
uncount(repeat_row)
# name1 name2
#1 x 0
#2 x 0
#3 y 1
#4 y 1
#5 z 2
CodePudding user response:
I just couldn't remember, but I thought there was a shorter way to do this:
df[sort(c(seq_len(nrow(df)), rep(which(df$name1 %in% c("x", "y")), 1))),]
name1 name2
1 x 0
1.1 x 0
2 y 1
2.1 y 1
3 z 2
CodePudding user response:
You can do this using tidyr::add_row
, but describe what you want to put into the row by using indexing.
library(tidyverse)
df <- data.frame(name1 = c("x","y","z"),
name2 = c(0,1,2))
df %>%
add_row(df[1,], .before = 2) %>%
add_row(df[2,], .before = 3)