我有以下数据表:
df = data.frame(id=c(1,1,1,1),timepoint=c("3 months","6 months","9 months","12 months"),
date=c("date1","date2","date3","date4"),bool=c("Y","Y","N","Y"),
name=c("abc","def","ghi","jkl"), stringsAsFactors=F)
我想将其转换为一行,id为id变量,如下所示:
library(reshape2)
melt = melt(df, id=c("id","timepoint"))
df2 = dcast(melt, id~variable+timepoint)
但是,这并没有按照我想要的顺序给出列,即:
df1 = df2[,c(1,3,7,11,4,8,12,5,9,13,2,6,10)]
我尝试使用下面的代码,它重新排序融化的表格,希望它能按照所需的顺序进行投射:
var.names = c("date", "bool","name")
times = c("3 months", "6 months", "9 months", "12 months")
melt = melt[order(melt$id, match(melt$timepoint, times), match(melt$variable, var.names)),]
但结果是一样的,似乎我需要以某种方式指定调用dcast的顺序,但我无法弄清楚如何做到这一点,所以非常感谢任何帮助!
非常感谢,如果我错过了一些明显的东西,请道歉。
答案 0 :(得分:2)
一种方法,
ind <- order(as.numeric(gsub('\\D+', '', names(df2[,-1]))))
df3 <- df2[c(1, ind+1)]