Likan Zhan

reshape

Likan Zhan · 2017-02-12

1. reshape a data frame from wide format to long format

d1 <- data.frame(subject = c("id1", "id2"),
x0 = c("male", "female"),
x1_2000 = 1:2,
x1_2005 = 5:6,
x2_2000 = 1:2,
x2_2005 = 5:6
)

d1
##   subject     x0 x1_2000 x1_2005 x2_2000 x2_2005
## 1     id1   male       1       5       1       5
## 2     id2 female       2       6       2       6
rs1 <- reshape(d1, dir = "long", varying = 3:6, sep = "_")
rs1
##        subject     x0 time x1 x2 id
## 1.2000     id1   male 2000  1  1  1
## 2.2000     id2 female 2000  2  2  2
## 1.2005     id1   male 2005  5  5  1
## 2.2005     id2 female 2005  6  6  2
d2 <- data.frame(subject = c("id1", "id2"),
x0 = c("male", "female"),
sample_1_2000 = 1:2,
sample_1_2005 = 5:6,
sample_2_2000 = 1:2,
sample_2_2005 = 5:6
)

d2
##   subject     x0 sample_1_2000 sample_1_2005 sample_2_2000 sample_2_2005
## 1     id1   male             1             5             1             5
## 2     id2 female             2             6             2             6
rs2 <- reshape(d2, dir = "long", varying = 3:6,
              split = list(regexp = "_20", include = TRUE))
rs2
##        subject     x0 time sample_1_ sample_2_ id
## 1.2000     id1   male 2000         1         1  1
## 2.2000     id2 female 2000         2         2  2
## 1.2005     id1   male 2005         5         5  1
## 2.2005     id2 female 2005         6         6  2
rs3 <- reshape(setNames(d2, sub("sample_", "", names(d2))),
               dir = "long", varying = 3:6, sep = "_")
rs3
##        subject     x0 time 1 2 id
## 1.2000     id1   male 2000 1 1  1
## 2.2000     id2 female 2000 2 2  2
## 1.2005     id1   male 2005 5 5  1
## 2.2005     id2 female 2005 6 6  2