Create duplicate columns in R for a large data frame
2
1
Entering edit mode
3.6 years ago

Hi all

I have a large data frame and I am trying to duplicate each column right beside the original one.

For example,

Input

V1 V2 V3
A T G

output

V1 V1 V2 V2 V3 V3
A A T T G G

Please let me know if there is a way to do this. Would it be possible to use rep() for this. Thanks in advance!

R dataframe • 3.1k views
ADD COMMENT
4
Entering edit mode
3.6 years ago

I don't know. Is this what you need?

df <- data.frame(
  a = c(1,2,3,4,5),
  b = c('a','b','c','d','e'),
  c = c(1,'b',3,'d',5),
  d = c('a',2,'c',4,'e'))
df
  a b c d
1 1 a 1 a
2 2 b b 2
3 3 c 3 c
4 4 d d 4
5 5 e 5 e

via apply()

do.call(cbind, apply(df, 2, function(x) data.frame(x,x)))
  a.x a.x.1 b.x b.x.1 c.x c.x.1 d.x d.x.1
1   1     1   a     a   1     1   a     a
2   2     2   b     b   b     b   2     2
3   3     3   c     c   3     3   c     c
4   4     4   d     d   d     d   4     4
5   5     5   e     e   5     5   e     e

via lapply()

do.call(cbind, lapply(df, function(x) data.frame(x,x)))
  a.x a.x.1 b.x b.x.1 c.x c.x.1 d.x d.x.1
1   1     1   a     a   1     1   a     a
2   2     2   b     b   b     b   2     2
3   3     3   c     c   3     3   c     c
4   4     4   d     d   d     d   4     4
5   5     5   e     e   5     5   e     e

Now going out for a jog. Catch you later

Kevin

ADD COMMENT
1
Entering edit mode

Hi Kevin, Thank you so much for your answer. It worked perfectly well!

ADD REPLY
2
Entering edit mode
3.6 years ago
> df <- data.frame(
+     a = c(1,2,3,4,5),
+     b = c('a','b','c','d','e'),
+     c = c(1,'b',3,'d',5),
+     d = c('a',2,'c',4,'e'))

> df
  a b c d
1 1 a 1 a
2 2 b b 2
3 3 c 3 c
4 4 d d 4
5 5 e 5 e

> data.frame(do.call(cbind,rep(df, each=2)), check.names = F)
  a a b b c c d d
1 1 1 a a 1 1 a a
2 2 2 b b b b 2 2
3 3 3 c c 3 3 c c
4 4 4 d d d d 4 4
5 5 5 e e 5 5 e e
ADD COMMENT

Login before adding your answer.

Traffic: 1940 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6