0
Follow
0
View

Repeat rows with specific value

jmshxy5233 注册会员
2023-01-24 22:57

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
zcc493841274 注册会员
2023-01-24 22:57

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)
sdjnyh2010 注册会员
2023-01-24 22:57

We may also do this as

library(dplyr)
library(tidyr)
df %>%  
   uncount(1 +(name1 %in% c('x', 'y')))
  name1 name2
1     x     0
2     x     0
3     y     1
4     y     1
5     z     2
yinfeng201 注册会员
2023-01-24 22:57

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
daihua1213 注册会员
2023-01-24 22:57

We could do it this way:

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

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