0

I know there are a lot of posts about how to repeat rows making the whole "repeated" rows following the "whole" original data. However, my question is a bit different, what I want is to repeat each row and let the newly created row becoming the next row of the repeated rows, meanwhile, I would like to create a new variable for each row.

To make my example clear, you can use this example data frame:

data.frame(a = c(1,2,3),b = c(1,2,3))
  a b
1 1 1
2 2 2
3 3 3

What I want to get is some data frame like this:

  a b type
1 1 1 origin
2 1 1 destination
3 2 2 origin
4 2 2 destination
5 3 3 origin
6 3 3 destination

Any hint will be much appreciated! Thanks for your help in advance

user438383
  • 5,716
  • 8
  • 28
  • 43
Jingjun
  • 177
  • 7

2 Answers2

0

You can repeat each row twice and repeat c('origin', 'destination') for each row.

In base R, you can do -

transform(df[rep(seq(nrow(df)), each = 2), ], type = c('origin', 'destination'))

Or in tidyverse -

library(dplyr)
library(tidyr)

df %>%
  uncount(2) %>%
  mutate(type = rep(c('origin', 'destination'), length.out = n()))

#  a b        type
#1 1 1      origin
#2 1 1 destination
#3 2 2      origin
#4 2 2 destination
#5 3 3      origin
#6 3 3 destination
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

Have a look at Repeat rows of a data.frame N times to see ways to repeat lines, and to bind another column you can use auto repetition.

cbind(x[rep(seq_len(nrow(x)), each = 2), ], type = c("origin", "destination"))
#    a b        type
#1   1 1      origin
#1.1 1 1 destination
#2   2 2      origin
#2.1 2 2 destination
#3   3 3      origin
#3.1 3 3 destination
GKi
  • 37,245
  • 2
  • 26
  • 48