Reshape a dataframe repeating columns in R
1
1
Entering edit mode
10.1 years ago
viniciushs88 ▴ 50

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 • 4.3k views
ADD COMMENT
5
Entering edit mode
10.1 years ago

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 COMMENT

Login before adding your answer.

Traffic: 2647 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