How to duplicate columns in a data frame

Is there an efficient way, without using for loops, to duplicate columns in a data frame? For example, if I have the following data frame:

  Var1 Var2
1    1    0
2    2    0
3    1    1
4    2    1
5    1    2
6    2    2

And I indicate that the column Var1 should be repeated twice, and the column Var2 three times, then I would like to get the following:

  Var1 Var1 Var2 Var2 Var2
1    1    1    0    0    0
2    2    2    0    0    0
3    1    1    1    1    1
4    2    2    1    1    1
5    1    1    2    2    2
6    2    2    2    2    2

Any help would be greatly appreciated!

+4
source share
1 answer

(rep), . data.frame , make.unique .1, .2 'df2'. , sub.

df2 <- df1[rep(names(df1), c(2,3))]
names(df2) <- sub('\\..*', '', names(df2))
df2
#  Var1 Var1 Var2 Var2 Var2
#1    1    1    0    0    0
#2    2    2    0    0    0
#3    1    1    1    1    1
#4    2    2    1    1    1
#5    1    1    2    2    2
#6    2    2    2    2    2

@Frank, ,

`[.noquote`(df1,c(1,1,2,2,2))
+3

Source: https://habr.com/ru/post/1606807/


All Articles