Chris Conner
2011-Dec-12 00:14 UTC
[R] using dcast to reshape a DF from long to wide with multiple measured variables per obs
I have data in the following format: person<- c(1,1,1,1,2,2,2,2,2,3,3,3,3,3,3) v2<- c("2011-01-01", "2011-02-01", "2011-03-01", "2011-04-01", "2011-01-01", "2011-02-01", "2011-03-01", "2011-04-01", "2011-05-01", "2011-01-01", "2011-02-01", "2011-03-01", "2011-04-01", "2011-05-01", "2011-06-01") v3 <- rep(30, 15) DF <-data.frame(person, v2, v3) DF$fillno <- with(DF, ave(person, person, FUN = seq)) DF$v2 <- as.Date(DF$v2) DF$v2 <- as.numeric(DF$v2) It represents data in long format that needs to be reshaped by person, with each fill number+v2 and fill number+v3 as a column, with missing values in cases where a person does not have a fill number. Essentially, I would like the DF to eventually assume the following strucutre: DFnew <- structure(list(person = 1:3, fillno1_v2 = c(14975L, 14975L, 14975L ), fillno1_v3 = c(30L, 30L, 30L), fillno2_v2 = c(15006L, 15006L, 15006L), fillno2_v3 = c(30L, 30L, 30L), fillno3_v2 = c(15034L, 15034L, 15034L), fillno3_v3 = c(30L, 30L, 30L), fillno4_v2 = c(15065L, 15065L, 15065L), fillno4_v3 = c(30L, 30L, 30L), fillno5_v2 = c(NA, 15095L, 15095L), fillno5_v3 = c(NA, 30L, 30L), fillno6_v2 = c(NA, NA, 15126L), fillno6_v3 = c(NA, NA, 30L)), .Names = c("person", "fillno1_v2", "fillno1_v3", "fillno2_v2", "fillno2_v3", "fillno3_v2", "fillno3_v3", "fillno4_v2", "fillno4_v3", "fillno5_v2", "fillno5_v3", "fillno6_v2", "fillno6_v3"), class = "data.frame", row.names = c(NA, -3L)) I have tried melt and dcast, but can only get reshape to organize by one measured variable at a time (and not two, as I would like). For example, the following organizes my data by fill-number and v2: dcast(DF, person ~ fillno, value.var=c("v2")) likewise the following works for v3 dcast(DF, person ~ fillno, value.var=c("v3")) But the following does not work: dcast(DF, person ~ fillno, value.var=c("v2", "v3")) and produces the following error: Error in .subset2(x, i, exact = exact) : subscript out of bounds Thank you in advance for any help you may be able to provide! Chris [[alternative HTML version deleted]]