Solidifying a melted data frame?

微笑、不失礼 提交于 2019-12-01 05:39:27

Try unstack:

dat <- read.table(text = "variable       value
1         A -0.19933093
2         A -1.19043346
3         A -1.32248172
4         A -1.98644507
5         A -0.07930953
6         B -0.10074686
7         B  0.72451483
8         B -0.40914044
9         B  0.02913376
10        B  0.16062491",sep = "",header = TRUE)

> unstack(dat,value~variable)

            A           B
1 -0.19933093 -0.10074686
2 -1.19043346  0.72451483
3 -1.32248172 -0.40914044
4 -1.98644507  0.02913376
5 -0.07930953  0.16062491

But I should add that I would love to know how to do this using dcast, as I've also tried repeatedly and haven't been able to.

Alright, begin with a data frame in wide form, containing an id. melt() it to give the long form, then dcast() it to get back to the original data frame.

library(reshape2)
df = read.table(text = "id   A   B
1  1 -0.19933093 -0.10074686
2  2 -1.19043346  0.72451483
3  3 -1.32248172 -0.40914044
4  4 -1.98644507  0.02913376
5  5 -0.07930953  0.16062491", sep = "", header = TRUE)

df

df.melt = melt(df, "id")
df.melt

df.original = dcast(df.melt, id~variable)

df.original

Using acast() to return a matrix. It needs an id variable.

library(reshape2)
dat <- read.table(text = "variable       value
1         A -0.19933093
2         A -1.19043346
3         A -1.32248172
4         A -1.98644507
5         A -0.07930953
6         B -0.10074686
7         B  0.72451483
8         B -0.40914044
9         B  0.02913376
10        B  0.16062491",sep = "",header = TRUE)

dat$id = rep(1:5, 2)
dat

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