Convert wide to long format in R

Posted by Anthony on Stack Overflow See other posts from Stack Overflow or by Anthony
Published on 2014-06-02T13:47:49Z Indexed on 2014/06/02 15:27 UTC
Read the original article Hit count: 228

Filed under:
|

My data has a long format similar to the one below:

ID Language  MotherTongue  SpokenatHome   HomeLang
1    English   English                      English
1    French                   French        
1    Polish    Polish         
2    Lebanese  Lebanese        Lebanese    Labanese
2    Arabic                    Arabbic

Here is the output I am looking for:

ID  Language1 Language2 Language 3  MotherTongue1  MotherTongue2  SpokenatHome1 HomeLan
1   English    French     Polish     English         Polish        French       English
2   Lebanese   Arabic                Labanese                      Arabic

I'm using using the melt and dcast functions of the reshape2 package, but it does not work. Does anyone know how to do this? Thanks.

df<-df[,c("OEN", "Langugae","MotherTongue", "SpokenatHome", "MainHomeLanguage")]
dfl <- melt(df, id.vars=c("OEN", "Langugae"), measure.vars=c("MotherTongue", "SpokenatHome", "MainHomeLanguage"),
            variable.name="Language")

dfw <- dcast(dfl, OEN ~  Langugae , value.var="value" )

© Stack Overflow or respective owner

Related posts about r

    Related posts about reshape2