How to “unmelt” data with reshape r

瘦欲@ 提交于 2019-11-30 06:39:51

I typically do this by creating an id column and then using dcast:

> dat
  variable     value
1       X1 0.4299397
2       X1 0.4299397
3       X1 0.4299397
4       X2 0.2531551
5       X2 0.2531551
6       X2 0.2531551
7       X3 0.3972119
8       X3 0.3972119
9       X3 0.3972119
> dat$id <- rep(1:3,times = 3)
> dcast(data = dat,formula = id~variable,fun.aggregate = sum,value.var = "value")
  id        X1        X2        X3
1  1 0.4299397 0.2531551 0.3972119
2  2 0.4299397 0.2531551 0.3972119
3  3 0.4299397 0.2531551 0.3972119

Depending on how robust you need this to be , the following will correctly cast for varying number of occurrences of variables (and in any order).

> variable<-c(rep("X1",5),rep("X2",4),rep("X3",3))
> value<-c(rep(rnorm(1,.5,.2),5),rep(rnorm(1,.5,.2),4),rep(rnorm(1,.5,.2),3))
> dat <-data.frame(variable,value)
> dat <- dat[order(rnorm(nrow(dat))),]
> dat
   variable     value
11       X3 1.0294454
8        X2 0.6147509
2        X1 0.3537012
7        X2 0.6147509
9        X2 0.6147509
5        X1 0.3537012
4        X1 0.3537012
12       X3 1.0294454
3        X1 0.3537012
1        X1 0.3537012
10       X3 1.0294454
6        X2 0.6147509
> dat$id = numeric(nrow(dat))
> for (i in 1:nrow(dat)){
+   dat_temp <- dat[1:i,]
+   dat[i,]$id <- nrow(dat_temp[dat_temp$variable == dat[i,]$variable,])
+ }
> cast(dat, id~variable, value = 'value')
  id        X1        X2       X3
1  1 0.3537012 0.6147509 1.029445
2  2 0.3537012 0.6147509 1.029445
3  3 0.3537012 0.6147509 1.029445
4  4 0.3537012 0.6147509       NA
5  5 0.3537012        NA       NA
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!