Impossible9
Impossible9

Reputation: 101

Specify order of columns of dcast output

I have the following data table:

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)

And I would like to cast this into one row, with id as the id variable as follows:

library(reshape2)
melt = melt(df, id=c("id","timepoint"))
df2 = dcast(melt, id~variable+timepoint)

However, this doesnt give me the columns in the order I would like, which is:

df1 = df2[,c(1,3,7,11,4,8,12,5,9,13,2,6,10)]

I tried using the code below, which reorders the melted table, in the hope that it would then cast in the desired order:

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)),]

But the result is the same, and it appears I need to somehow specify the ordering in the call to dcast, but I can't figure out how to do this, and so would greatly appreciate any help!

Thank you very much, and apologies if I have missed something obvious.

Upvotes: 1

Views: 909

Answers (1)

Sotos
Sotos

Reputation: 51592

One way to do it,

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

Upvotes: 2

Related Questions