1

我有以下数据集

    D<-structure(list(P = structure(c(3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 
1L, 1L, 2L, 2L, 2L, 2L, 2L), .Label = c("A", "B", "E"), class = "factor"), 
    ht = structure(c(4L, 2L, 3L, 5L, 1L, 4L, 2L, 3L, 5L, 1L, 
    4L, 2L, 3L, 5L, 1L), .Label = c("CH", "L65", "M65", "NOC", 
    "SPAR"), class = "factor"), hol = c(1L, 1L, 1L, 2L, 1L, 1L, 
    1L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L), un = c(2L, 2L, 2L, 1L, 
    2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L), fu = c(3L, 3L, 
    3L, 3L, 3L, 5L, 5L, 6L, 5L, 5L, 3L, 3L, 3L, 3L, 3L)), .Names = c("P", 
"ht", "hol", "un", "fu"), class = "data.frame", row.names = c(NA, 
-15L))

我想依次使用 ht 和 hol、un、fu 的每个可能值,以便它从

  P   ht hol un fu
1  E  NOC   1  2  3
2  E  L65   1  2  3
3  E  M65   1  2  3
5  E   CH   1  2  3
6  A  NOC   1  2  5
7  A  L65   1  2  5
9  A  M65   2  1  6

... 到

R        E  A
NOC_hol  1  1
NOC_un   2  2
NOC_fu   3  5
...
M65_fu   3  6

我正在努力寻找一种简单的方法,这是我第一次使用 reshape,所以我有点迷茫。

4

1 回答 1

1

融化,然后重塑:

library(reshape2)

dcast(melt(D), ht + variable ~ P)
#     ht variable A B E
#1    CH      hol 1 2 1
#2    CH       un 2 1 2
#3    CH       fu 5 3 3
#4   L65      hol 1 1 1
#5   L65       un 2 2 2
#6   L65       fu 5 3 3
#7   M65      hol 2 1 1
#8   M65       un 1 2 2
#9   M65       fu 6 3 3
#10  NOC      hol 1 1 1
#11  NOC       un 2 2 2
#12  NOC       fu 5 3 3
#13 SPAR      hol 2 2 2
#14 SPAR       un 1 1 1
#15 SPAR       fu 5 3 3

paste如果愿意,您可以将前两列放在一起。

于 2013-08-20T22:50:54.383 回答