Melt and add data using reshape2 functions in R

It should be simple, but for some reason I was stuck. I have data that looks like

A <- data.frame(x=rnorm(10), y=rnorm(10), z=rnorm(1)) B <- data.frame(x=rnorm(10), y=rnorm(10), z=rnorm(1)) C <- data.frame(x=rnorm(10), y=rnorm(10), z=rnorm(1)) method1 <- list(A=A,B=B,C=C) method2 <- list(A=A,B=B,C=C) biglist <- list(method1, method2) 

And I would like to reformat the data so that it looks like

 xyz dataset method - - - --- ----- 1 1 1 A 1 1 0 2 A 1 1 0 3 A 1 1 1 3 A 1 1 1 1 B 1 1 0 2 B 1 1 0 3 B 1 1 1 3 B 1 1 1 1 C 1 1 0 2 C 1 1 0 3 C 1 1 1 3 C 1 1 1 1 A 2 1 0 2 A 2 1 0 3 A 2 1 1 3 A 2 1 1 1 B 2 1 0 2 B 2 ... 

melt doesn't quite do what I want, because it destroys my x / y / z variable headers.

+4
source share
1 answer

Your data files must have a primary key, for example, an identifier column or a column with unique values ​​- otherwise you end up with the x, y, z coordinates of the point in several unrelated rows. I assume x is such a column.

You may also need to call dcast after melt if the resulting data.frame is too vertical.

 library(reshape2) d <- melt(biglist, id.vars="x") d <- dcast( d, L1 + L2 + x ~ variable ) 
+6
source

Source: https://habr.com/ru/post/1394525/


All Articles