dat.w <- data.frame(id = c(23, 55, 71),
gend = c("male", "female", "male"), age = c(22, 19, 26),
adep = c(3, 6, NA), bdep = c(5, 5, 6), cdep = c(4, NA, 5),
aanx = c(5, 3, 6), banx = c(NA, 7, 2), canx = c(6, NA, 8))
#----------------------------------------------------------------------------
# Convert from 'wide' data format to the 'long' data format
# Example 1: One set of time-varying variables combined into "dep"
df.long(dat.w, var = c("adep", "bdep", "cdep"), var.name = "dep", idvar = "id")
# Example 2: Select time-invariant variables 'gend' and 'age'
df.long(dat.w, gend, age, var = c("adep", "bdep", "cdep"), var.name = "dep",
idvar = "id")
# Example 3: Newly created variable "type" as character vector
df.long(dat.w, age, var = c("adep", "bdep", "cdep"), var.name = "dep",
idvar = "id", time = "chr", time.name = "type")
# Example 4: User-defined variable "type"
df.long(dat.w, age, var = c("adep", "bdep", "cdep"), var.name = "dep",
idvar = "id", time = c("pre", "post", "follow-up"), time.name = "type")
# Example 5: Two sets of time-varying variables combined into "dep" and "anx"
df.long(dat.w, age,
var = list(c("adep", "bdep", "cdep"), c("aanx", "banx", "canx")),
var.name = c("dep", "anx"), idvar = "id")
# Alternative specification using named lists for the argument 'var'
df.long(dat.w, age,
var = list(dep = c("adep", "bdep", "cdep"), anx = c("aanx", "banx", "canx")),
idvar = "id")
# Example 6: Remove rows with only NA values
df.long(dat.w, age, var = list(c("adep", "bdep", "cdep"), c("aanx", "banx", "canx")),
idvar = "id", sort = FALSE, na.rm = TRUE)
# Example 7: Convert all variables except "age" and "gend"
df.long(dat.w, age, gend, idvar = "id")
#----------------------------------------------------------------------------
# Convert from 'long' data format to the 'wide' data format
dat.l <- df.long(dat.w,
var = list(c("adep", "bdep", "cdep"), c("aanx", "banx", "canx")),
var.name = c("dep", "anx"), idvar = "id")
# Example 8: Time-varying variables "dep" and "anx" expanded into multiple variables
df.wide(dat.l, var = c("dep", "anx"), idvar = "id", time = "time")
# Example 9: Select time-invariant variables 'age'
df.wide(dat.l, age, var = c("dep", "anx"), idvar = "id", time = "time")
# Example 10: Variable name prefix of the expanded variables "depre" and "anxie"
# with separating character "."
df.wide(dat.l, var = c("dep", "anx"), var.name = c("depre", "anxie"),
idvar = "id", time = "time", sep = ".")
Run the code above in your browser using DataLab