The melt/cast functions in the reshape package are great, but I\'m not sure if there is a simple way to apply them when measured variables are of different types. For example,
I think the reshape
function in the stats package is simplest. Here is a simple example, does this do what you want?
> tmp
id val val2 cat
1 1 1 14 a
2 1 2 13 b
3 2 3 12 b
4 2 4 11 a
> tmp2 <- tmp
> tmp2$t <- ave(tmp2$val, tmp2$id, FUN=seq_along)
> tmp2
id val val2 cat t
1 1 1 14 a 1
2 1 2 13 b 2
3 2 3 12 b 1
4 2 4 11 a 2
> reshape(tmp2, idvar='id', timevar='t', direction='wide')
id val.1 val2.1 cat.1 val.2 val2.2 cat.2
1 1 1 14 a 2 13 b
3 2 3 12 b 4 11 a
Hopefully your patients sex is not changing each appointment, but there could be other categorical variables that change between visits
You can process each variable separately, and join the resulting two data.frames.
# Sample data
n <- 5
d <- data.frame(
id = 1:n,
pt1 = sample(c("M","F"),n,replace=TRUE),
wt1 = round(runif(n,100,200)),
pt2 = sample(c("M","F"),n,replace=TRUE),
wt2 = round(runif(n,100,200)),
pt3 = sample(c("M","F"),n,replace=TRUE),
wt3 = round(runif(n,100,200))
)
# Reshape the data.frame, one variable at a time
library(reshape2)
d1 <- melt(d,
id.vars="id", measure.vars=c("pt1","pt2","pt3"),
variable.name="patient", value.name="gender"
)
d2 <- melt(d,
id.vars="id", measure.vars=c("wt1","wt2","wt3"),
variable.name="patient", value.name="weight"
)
d1$patient <- as.numeric(gsub("pt", "", d1$patient))
d2$patient <- as.numeric(gsub("wt", "", d1$patient))
# Join the two data.frames
merge(d1, d2, by=c("id","patient"), all=TRUE)