dataset - Using unstack in R -


i have data frame wish transpose long wide form. advisor suggested using unstack , wrote bit of sample code me out. i'm able run sample code fine (with placeholder variables) having trouble applying data. here "sample code: "

data1 <- data.frame( dwnstid = c(1, 1, 2, 2, 2), load = c(3, na, 10, na, na), x1 = c(10,14, 20, 40, 10), x2=c(3,5,1,2,3), z1 = c(0.2, 0.7, 0.4, 0.3,0.2) ) oo <- order(data1$dwnstid) data1 <- data1[oo,] y <- data1$load[!is.na(data1$load)] id <- as.numeric(ordered(data1$dwnstid)) idtbl <- table(id) ns <- max(idtbl) nr <- max(id) my.unstack <- function(x, id, nc=ns, x.names){ temp <- tapply(data1$x1, data1$dwnstid, fun=function(x, ns=nc){ tt <- as.vector(x) if (length(tt) < ns) tt <- c(tt, rep(0, ns-length(tt))) return(tt)}) temp <- as.data.frame(matrix(unlist(temp), nrow=nr, ncol=ns, byrow=t)) names(temp) <- x.names return(temp) } x1.names <- paste("x1", 1:ns, sep="_") x2.names <- paste("x2", 1:ns, sep="_") z1.names <- paste("z1", 1:ns, sep="_") x1 <- my.unstack(data1$x1, data1$dwnstid, nc=ns, x1.names) x2 <- my.unstack(data1$x2, data1$dwnstid, nc=ns, x2.names) z1 <- my.unstack(data1$z1, data1$dwnstid, nc=ns, z1.names) data1_reshaped <- cbind (y, x1,x2, z1) 

and here code variables of interest plugged in (i've omitted parts didn't need change/ran fine since didn't want clutter post more have):

x1 <- data1$ag[!is.na(data1$ag)] x2 <- data1$nonag[!is.na(data1$nonag)] z1 <- data1$hsg[!is.na(data1$hsg)]  x1.names <- paste("x1", 1:ns, sep="_") x2.names <- paste("x2", 1:ns, sep="_") z1.names <- paste("z1", 1:ns, sep="_") x1 <- my.unstack(data1$x1, data1$dwnstid, nc=ns, x1.names) x2 <- my.unstack(data1$x2, data1$dwnstid, nc=ns, x2.names) z1 <- my.unstack(data1$z1, data1$dwnstid, nc=ns, z1.names) data1_reshaped <- cbind (y, x1,x2, z1) 

can clue me in why last 4 lines not run? getting message vectors of different lengths not sure how take care of problem. specifically, x1, x2, , z1 1 length, x1.names, x2.names, , z1.names different length. isn't problem inherent when reshaping data? i'm not expecting solve problem me, appreciate advice on can try @ point.

my goal each row in data frame correspond load value, while columns ag1, ag2, ag3, , on.

this should there because takes care of different dimension issue. repeat each var of interest , merge together.

library(data.table) data1 <- data.frame( dwnstid = c(1, 1, 2, 2, 2), load = c(3, na, 10, na, na), x1 = c(10,14, 20, 40, 10), x2=c(3,5,1,2,3), z1 = c(0.2, 0.7, 0.4, 0.3,0.2) )  data1.dt <- data.table(data1) data1.dt[,"group.id" := seq_len(.n), by=dwnstid]  datax1 <- data1.dt[,c("dwnstid", "x1", "group.id"),with=false] x1 <- reshape(datax1, timevar = "group.id",  idvar = 'dwnstid', direction = "wide") 

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -