r - More elegant way of transforming data frames from wide to long data fromat by using reshape() or melt() -
i looking more elegant way of reshaping data frame using melt (reshape2) or reshape function.
let’s assume have simple data frame this:
d<-data.frame("pid"=factor(c(1,1,1,2,2,2)), "cue1"=factor(c(1,2,3,1,2,3)), "cue2"=factor(c(5,5,5,5,5,5)))
and transform second , third columns single long one. code below works looking more elegant way:
d1<-data.frame("trigger"=as.vector(t(d[,c(2:3)]))) d1$pid<-factor(rep(c(1,2),each=6))
it important number of levels of 2 factors different (cue1 has 3, cue2 has 1 level). code above gives me new column looks (this want):
trigger 1 5 2 5 3 5 ...
unfortunately, of examples on internet reshape discusses following (and in case, non-preferred) example:
trigger 1 2 3 1 2 3 ...
but need former one.
thanks suggestions in advance.
if looking one-liner using melt, below approach (the order desired kept):
# assume df data frame df_new = data.frame(trigger = melt(t(df[,2:3]))[,3], pid = rep(df[,1], each=2)) df_new # trigger pid # 1 1 1 # 2 5 1 # 3 2 1 # 4 5 1 # 5 3 1 # 6 5 1 # 7 1 2 # 8 5 2 # 9 2 2 # 10 5 2 # 11 3 2 # 12 5 2
Comments
Post a Comment