Solidification of the molten data frame?

Assuming I have a molten data.frame that looks like this:

  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 

How do I get:

  AB -0.19933093 -0.10074686 -1.19043346 0.72451483 -1.32248172 -0.40914044 -1.98644507 0.02913376 -0.07930953 0.16062491 

Seems trivial, but I'm confusing the answer. dcast and acast don't seem to do this. My goal is to do this on large datasets and turn the final product into a matrix with column names that will be variable names. I tried playing with daply and laply (before melting) without much success.

+6
source share
3 answers

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) AB 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 have to add that I would be interested to know how to do this using dcast , since I also tried many times and failed.

+8
source

Well, start with a broad-format data frame containing an identifier. melt() to give a long form, then dcast() to return to the original data frame.

 library(reshape2) df = read.table(text = "id AB 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 
+3
source

Using acast() to return a matrix. He 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) 
+2
source

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


All Articles