Paul Tansley
Paul Tansley

Reputation: 181

Repeat (duplicate) just one row twice in R

I'm trying to duplicate just the second row in a dataframe, so that row will appear twice. A dplyr or tidyverse aproach would be great. I've tried using slice() but I can only get it to either duplicate the row I want and remove all the other data, or duplicate all the data, not just the second row.

So I want something like df2:

df <- data.frame(t = c(1,2,3,4,5),
                 r = c(2,3,4,5,6))

df1 <- data.frame(t = c(1,2,2,3,4,5),
                  r = c(2,3,3,4,5,6))

Thanks!

Upvotes: 1

Views: 229

Answers (2)

arg0naut91
arg0naut91

Reputation: 14774

Here's also a tidyverse approach with uncount:

library(tidyverse)

df %>%
  mutate(nreps = if_else(row_number() == 2, 2, 1)) %>%
  uncount(nreps)

Basically the idea is to set the number of times you want the row to occur (in this case row number 2 - hence row_number() == 2 - will occur twice and all others occur only once but you could potentially construct a more complex feature where each row has a different number of repetitions), and then uncount this variable (called nreps in the code).

Output:

    t r
1   1 2
2   2 3
2.1 2 3
3   3 4
4   4 5
5   5 6

Upvotes: 3

Ronak Shah
Ronak Shah

Reputation: 389355

One way with slice would be :

library(dplyr)
df %>% slice(sort(c(row_number(), 2)))

#  t r
#1 1 2
#2 2 3
#3 2 3
#4 3 4
#5 4 5
#6 5 6

Also :

df %>% slice(sort(c(seq_len(n()), 2)))

In base R, this can be written as :

df[sort(c(seq(nrow(df)), 2)), ]

Upvotes: 1

Related Questions