-2

I have a table contain text of information and I need to replicate each column 3 times

for example

A001 A002 
A003 A004 

I want to make it

A001 A001 A001 A002 A002 A002 
A003 A003 A003 A004 A004 A004 

Is there way to do that for whole table?

zx8754
  • 52,746
  • 12
  • 114
  • 209
Faisal
  • 1
  • Welcome to StackOverflow! Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). This will make it much easier for others to help you. – Sotos Sep 12 '17 at 06:21

2 Answers2

3

You can repeat names of dataframe n (here 3) number of times using rep

rep(names(df), each=3)

#[1] "V1" "V1" "V1" "V2" "V2" "V2"

and then

df[rep(names(df), each = 3)]

#    V1 V1.1 V1.2   V2 V2.1 V2.2
#1 A001 A001 A001 A002 A002 A002
#2 A003 A003 A003 A004 A004 A004

data

df <- structure(list(V1 = structure(1:2, .Label = c("A001", "A003"), 
      class = "factor"),V2 = structure(1:2, .Label = c("A002", "A004"), 
      class = "factor")), .Names = c("V1","V2"), class = "data.frame", 
      row.names = c(NA, -2L))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

Another way is to use replicate, i.e. -- (Using @Ronak's example)

do.call(cbind, replicate(3, list(df)))

which gives,

    V1   V2   V1   V2   V1   V2
1 A001 A002 A001 A002 A001 A002
2 A003 A004 A003 A004 A003 A004

To sort the columns to match your expected output (and make the names unique),

dd <- do.call(cbind, replicate(3, list(df)))

dd[order(gsub('\\D+', '', names(dd)))]

which gives,

    V1 V1.1 V1.2   V2 V2.1 V2.2
1 A001 A001 A001 A002 A002 A002
2 A003 A003 A003 A004 A004 A004
Sotos
  • 51,121
  • 6
  • 32
  • 66