【问题标题】:Specify order of columns of dcast output指定 dcast 输出的列顺序
【发布时间】:2016-08-18 09:09:30
【问题描述】:

我有如下数据表:

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 时以某种方式指定顺序,但我不知道如何执行此操作,因此非常感谢任何帮助!

非常感谢,如果我遗漏了一些明显的东西,我们深表歉意。

【问题讨论】:

    标签: r reshape2 dcast


    【解决方案1】:

    一种方法,

    ind <- order(as.numeric(gsub('\\D+', '', names(df2[,-1]))))
    df3 <- df2[c(1, ind+1)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-28
      • 1970-01-01
      相关资源
      最近更新 更多