adam.888
adam.888

Reputation: 7846

Expanding variable number of columns in a dataframe

I have a data frame that can have a varying number of columns and I need to expand each column out automatically two more times before the next one:

Example:

df <- data.frame(a=1:10,b=2:11,c=3:12)
df

I tried

dfexpand <- df[,rep(colnames(df),3)]
dfexpand

But this gives the columns in the order in this case:

a  b  c a.1 b.1 c.1 a.2 b.2 c.2

But I need the order in this case as:

a a.1 a.2 b b.1 b.2 c c.1 c.2

Upvotes: 2

Views: 60

Answers (1)

David Heckmann
David Heckmann

Reputation: 2939

use the each argument to rep():

dfexpand <- df[,rep(colnames(df),each=3)]

Upvotes: 3

Related Questions