duplicate every row in a table and add a suffix with dplyr in r

You can use the bind_rows() function from dplyr package to bind the original data with a duplicated copy of itself. Then, use the mutate() function to add a suffix to a column indicating the original and duplicated copies. Here's an example:

main.r
library(dplyr)

df <- data.frame(ID = c(1, 2, 3),
                 Name = c("John", "Mary", "Peter"))

df_dup <- df %>%
  bind_rows(df) %>% # duplicate all rows
  mutate(Suffix = ifelse(row_number() <= nrow(df), "_original", "_duplicated")) # add suffix

# Output
df_dup
#>   ID  Name         Suffix
#> 1  1  John    _original
#> 2  2  Mary    _original
#> 3  3 Peter    _original
#> 4  1  John _duplicated
#> 5  2  Mary _duplicated
#> 6  3 Peter _duplicated
459 chars
19 lines

In this example, each row was duplicated and a suffix was added to the Suffix column to indicate whether it is the original or duplicated copy of the data. The ifelse() statement checks the current row number against the number of rows in the original data frame to add the appropriate suffix.

gistlibby LogSnag