转换R中的data.frame

时间:2013-02-01 06:02:03

标签: r dataframe transform

我有以下数据框:

foo <- data.frame( abs( cbind(rnorm(3),rnorm(3, mean=.8),rnorm(3, mean=.9),rnorm(3, mean=1))))
colnames(foo) <- c("w","x","y","z")
rownames(foo) <- c("n","q","r")
foo
#            w         x         y         z
# n 1.51550092 1.4337572 1.2791624 1.1771230
# q 0.09977303 0.8173761 1.6123402 0.1510737
# r 1.17083866 1.2469347 0.8712135 0.8488029

我想要做的是将其改为:

newdf
# 1     n    w 1.51550092
# 2     q    w 0.09977303
# 3     r    w 1.17083866
# 4     n    x 1.43375725
# 5     q    x 0.81737606
# 6     r    x 1.24693468
# 7     n    y 1.27916241
# 8     q    y 1.61234016
# 9     r    y 0.87121353
# 10    n    z 1.17712302
# 11    q    z 0.15107369
# 12    r    z 0.84880292

这样做的方法是什么?

2 个答案:

答案 0 :(得分:8)

几种方法可以做到这一点。这是一个:

set.seed(1)
foo <- data.frame( abs( cbind(rnorm(3),
                              rnorm(3, mean=.8),
                              rnorm(3, mean=.9),
                              rnorm(3, mean=1))))
colnames(foo) <- c("w","x","y","z")
rownames(foo) <- c("n","q","r")
foo
#           w          x        y         z
# n 0.6264538 2.39528080 1.387429 0.6946116
# q 0.1836433 1.12950777 1.638325 2.5117812
# r 0.8356286 0.02046838 1.475781 1.3898432
data.frame(rows = row.names(foo), stack(foo))
#    rows     values ind
# 1     n 0.62645381   w
# 2     q 0.18364332   w
# 3     r 0.83562861   w
# 4     n 2.39528080   x
# 5     q 1.12950777   x
# 6     r 0.02046838   x
# 7     n 1.38742905   y
# 8     q 1.63832471   y
# 9     r 1.47578135   y
# 10    n 0.69461161   z
# 11    q 2.51178117   z
# 12    r 1.38984324   z

答案 1 :(得分:6)

reshape2:::melt()特别适合这种转变:

library(reshape2)

foo <- cbind(ID=rownames(foo),  foo)
melt(foo)
# Using ID as id variables
#    ID variable     value
# 1   n        w 1.7337416
# 2   q        w 0.5890877
# 3   r        w 0.2245508
# 4   n        x 0.5237346
# 5   q        x 0.9320455
# 6   r        x 0.8156573
# 7   n        y 1.9287306
# 8   q        y 1.1604229
# 9   r        y 1.7631215
# 10  n        z 0.3591350
# 11  q        z 0.9740170
# 12  r        z 0.5621968