Dcast 2 Column

I have the following data.frame:

group <- sample(c("egyptian", "american", "irish", "australian"), 50, TRUE)
E <- c(rnorm(50, 5, 6))
F <- c(rnorm(50, 7.8, 4.5))
G <- c(rnorm(50, 65, 16.7))
test <- data.frame(group=group, E=E, F=F, G=G)

My goal is to generate data.frameone that includes groupas a heading and lists its corresponding values ​​in Ebelow.

something like this data.frame:

egyptian <- c(rnorm(50,5,6))
american<- c(rnorm(50,5,6))
irish<- c(rnorm(50,5,6))
australian<- c(rnorm(50,5,6)) 
test <- data.frame(egyptian=egyptian, american=american, 
                   irish=irish, australian=australian)

I tried to multiply 2 columns and then use dcast,, but that failed. Is dcast2 columns possible from long to wide?

+4
source share
1 answer

As @jbaums noted in the comments, the size of each group is not the same.

  table(test$group)
  # american australian   egyptian      irish 
  #   7         18          9         16 

It is also best to set the seed to make it reproducible. i.e.

  set.seed(1)
  group <- sample(c("egyptian", "american", ....)

( "E" ), , ( "" )

library(reshape2) 
test$ind <- with(test, ave(seq_along(group), group, FUN=seq_along))
dcast(test, ind~group, value.var='E')

base R xtabs

xtabs(E~ind+group, test)

, "0" . dcast "NA" , fill.

+2

All Articles