0

I am looking for a way to copy a column "col1" x times and appending each of these copies with one of x strings from a character vector. Example:

df <- data.frame(col1 = c(1,2,3,4,5))
suffix <- c("a", "b", "c")

resulting in:

df_suffix <- data.frame(col1 = c(1,2,3,4,5), col1_a = c(1,2,3,4,5), col1_b = c(1,2,3,4,5), col1_c = c(1,2,3,4,5))

  col1 col1_a col1_b col1_c
1    1      1      1      1
2    2      2      2      2
3    3      3      3      3
4    4      4      4      4
5    5      5      5      5
Michael
  • 1,281
  • 1
  • 17
  • 32

1 Answers1

2

You can use paste() to create the new columns inside df, and assign them the values of the first column:

df[,paste(names(df), suffix, sep = "_")] <- df[,1]
#  col1 col1_a col1_b col1_c
#1    1      1      1      1
#2    2      2      2      2
#3    3      3      3      3
#4    4      4      4      4
#5    5      5      5      5
mtoto
  • 23,919
  • 4
  • 58
  • 71