This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Reshape a dataframe repeating columns in R

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!

reshape r

1 answer

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

Log in to answer this question.