Skip to content

Instantly share code, notes, and snippets.

@spsaaibi
Last active August 29, 2015 14:02
Show Gist options
  • Save spsaaibi/6d7b5c6a7c9d7d06c75f to your computer and use it in GitHub Desktop.
Save spsaaibi/6d7b5c6a7c9d7d06c75f to your computer and use it in GitHub Desktop.
Reshaping wide to long data.frames
## transform an arbitrary 'wide' data.frame into a 'long' data.frame.
# load packages
library(reshape)
# sample wide data.frame
wide.df <- data.frame(Code = c("PPP001","PPP002"),
Country = c("ESP","FRA"), January2012 = c(110,50), February2012 = c(40,55),
March2012 = c(56,32))
## Flags
n.fixed.vars <-2 # how many vars you want to leave 'fixed'
v.names <- "Sales" # names of your time-varying variable
idvar <- names(long.df)[seq(n.fixed.vars)] # names of your fixed variables
timevar <- "Month" # name of the frequency of variation
long.df <- reshape(wide.df,
direction="long",
varying=list(names(long.df)[(n.fixed.vars+1):ncol(long.df)]),
v.names=v.names,
idvar=idvar,
timevar=timevar,
times=names(long.df)[(n.fixed.vars+1):ncol(long.df)])
rownames(long.df) <- NULL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment