Transforming data.frame in R

左心房为你撑大大i 提交于 2019-12-20 01:45:22

问题


I have the following data frame:

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

What I want to do is to change it into :

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

What's the way to do it?


回答1:


reshape2:::melt() is particularly well suited to this transformation:

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



回答2:


There are several ways to do this. Here's one:

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


来源:https://stackoverflow.com/questions/14640668/transforming-data-frame-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!