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?
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?
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))
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