Question

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
Was it helpful?

Solution

You can use melt and dcast from "reshape2", but you'll have to melt twice. Assuming your source data.frame is called "mydf".

The first melt

library(reshape2)
dfL1 <- melt(mydf, id.vars=c("Name", "Chr", "Position"), variable.name="V1")
head(dfL1)
#   Name Chr Position    V1 value
# 1 Pro1   1       25 NE001  -0.3
# 2 Pro2   2       23 NE001  -0.4
# 3 Pro3   3       30 NE001  -0.3
# 4 Pro1   1       25 NE002   0.2
# 5 Pro2   2       23 NE002   0.2
# 6 Pro3   3       30 NE002   0.2

The second melt

dfL2 <- melt(dfL1, id.vars=c("Name", "V1"), variable.name="V2")
head(dfL2)
#   Name    V1  V2 value
# 1 Pro1 NE001 Chr     1
# 2 Pro2 NE001 Chr     2
# 3 Pro3 NE001 Chr     3
# 4 Pro1 NE002 Chr     1
# 5 Pro2 NE002 Chr     2
# 6 Pro3 NE002 Chr     3

The reshaping step

dcast(dfL2, V1 ~ Name + V2)
#      V1 Pro1_Chr Pro1_Position Pro1_value Pro2_Chr Pro2_Position Pro2_value
# 1 NE001        1            25       -0.3        2            23       -0.4
# 2 NE002        1            25        0.2        2            23        0.2
# 3 NE003        1            25        0.4        2            23       -0.3
#   Pro3_Chr Pro3_Position Pro3_value
# 1        3            30       -0.3
# 2        3            30        0.2
# 3        3            30        0.4
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top