Alternatives to stats::reshape

后端 未结 2 1310
傲寒
傲寒 2021-02-10 08:14

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,

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-10 08:38

    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)
    

提交回复
热议问题