how can i create duplicate row under each row

  1. i want to create a blank duplicate row with same id under each row

  2. i also want to create duplicate row under each row which is exactly duplicate of top row

Hi,

Here is an example of one implementation:

library(dplyr)

#Original data
myDf = data.frame(x = 1:5, y = runif(5), z = LETTERS[1:5])

#Add blank row with same ID
newDf = rbind(myDf, myDf %>% mutate(y = NA, z = NA)) %>% arrange(x)
newDf
#>    x          y    z
#> 1  1 0.81425440    A
#> 2  1         NA <NA>
#> 3  2 0.06461431    B
#> 4  2         NA <NA>
#> 5  3 0.21991112    C
#> 6  3         NA <NA>
#> 7  4 0.24515161    D
#> 8  4         NA <NA>
#> 9  5 0.43092217    E
#> 10 5         NA <NA>

#Add duplicate row with same ID
newDf = rbind(myDf, myDf) %>% arrange(x)
newDf
#>    x          y z
#> 1  1 0.81425440 A
#> 2  1 0.81425440 A
#> 3  2 0.06461431 B
#> 4  2 0.06461431 B
#> 5  3 0.21991112 C
#> 6  3 0.21991112 C
#> 7  4 0.24515161 D
#> 8  4 0.24515161 D
#> 9  5 0.43092217 E
#> 10 5 0.43092217 E

Created on 2020-09-09 by the reprex package (v0.3.0)

Hope this helps,
PJ

2 Likes

Hi,

Here is an example again:

library(dplyr)

#Generate the data
myDf = as.data.frame(matrix(runif(15*300), nrow = 300, ncol = 15)) %>% 
  mutate(V1 = 1:300)
colnames(myDf)  = paste0("c", 1:15)

#Create the duplicates with only the first 5 columns' values
duplicates = myDf
duplicates[,6:15] = NA

newDf = rbind(myDf, duplicates) %>% arrange(c1)

PJ

1 Like

it is really helpful thank you

great
thank you very much.

1 Like

both the codes are really solutions for my prob. but i am allowed to mark only one

Hi,

Don't worry, you should just pick the post that provided the biggest contribution to the solution if multiple options.

PJ

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.