Question: Reshape a dataframe repeating columns in R
1
gravatar for viniciushs88
3.6 years ago by
viniciushs8850
Germany
viniciushs8850 wrote:

 

I would like to reshape a dataframe and repeat some informations about Name strings ("Pro1", "Pro2" and "Pro3").

My input:

Name Chr Position  NE001  NE002  NE003
Pro1  1     25     -0.3    0.2   0.4
Pro2  2     23     -0.4    0.2  -0.3
Pro3  3     30     -0.3    0.2   0.4 

My expected output:

Sample    Pro1  Chr  Position   Pro2   Chr  Position   Pro3  Chr  Position
NE001    -0.3    1     25      -0.4     2     23      -0.3    3      30
NE002     0.2    1     25       0.2     2     23       0.2    3      30
NE003     0.4    1     25      -0.3     2     23       0.4    3      30

Cheers!

R reshape • 1.5k views
ADD COMMENTlink modified 3.6 years ago by Malachi Griffith16k • written 3.6 years ago by viniciushs8850
5
gravatar for Devon Ryan
3.6 years ago by
Devon Ryan73k
Freiburg, Germany
Devon Ryan73k wrote:

Given your input as a dataframe or matrix named d:

d2 <- t(d[,-c(1:3)])
d2 <- cbind(d2, matrix(rep(d[,2], each=nrow(d2)), nrow=nrow(d2)),
    matrix(rep(d[,3], each=nrow(d2)), nrow=nrow(d2)))
colnames(d2) <- c(as.character(d$Name),rep("Chr", nrow(d2)), rep("Position", nrow(d2)))
d2 <- d2[,c(1,4,7,2,5,8,3,6,9)]

 

The output is:

> d2
      Pro1 Chr Position Pro2 Chr Position Pro3 Chr Position
NE001 -0.3   1       25 -0.4   2       23 -0.5   3       30
NE002  0.2   1       25  0.2   2       23  0.2   3       30
NE003  0.4   1       25 -0.3   2       23  0.4   3       30

 

ADD COMMENTlink modified 3.6 years ago • written 3.6 years ago by Devon Ryan73k
Please log in to add an answer.

Help
Access

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 1097 users visited in the last hour