[R] Wide to long format in R

PIKAL Petr petr@p|k@| @end|ng |rom prechez@@cz
Tue May 18 08:29:45 CEST 2021


Hi

Please do not post in HTML formating, your messages are then messy. Better
to show how your data frame look like is something like

dput(bop.df[1:10,]) 

Anyway, melt/cast functions from reshape2 package are quite handy for such
tasks.

Cheers
Petr

> -----Original Message-----
> From: R-help <r-help-bounces using r-project.org> On Behalf Of Admire Tarisirayi
> Chirume
> Sent: Monday, May 17, 2021 9:44 AM
> To: r-help using r-project.org
> Subject: [R] Wide to long format in R
> 
> I need help on reshaping my data frame which is currently in wide format.
> 
> I ran the following codes to create panel ids based on the variable for
country
> names  "*Country"; *
> 
> *bop.df$id<-as.numeric(as.factor(bop.df$Country))*
> 
> then ran the code below to reshape from wide to long format;
> 
> *reshaped.bop <- pivot_longer(bop.df,3:17,names_to =  "year", values_to =
> "value")*
> 
> by running the code:  *print( reshaped.bop), the following table in long
> format came out;*
> 
> 
> Country year bank_ratio Reserve_ratio broad_money id Angola 2006 24 77
> 163 1 Angola 2007 25 59 188 1 Botswana 2008 38 64 317 1 Botswana 2009 34
65
> 361 1 Zimbabwe 2010 42 57 150 1 Zimbabwe 2006 49 86 288 2
> 
> 
> This, however, is not what i wanted. kindly help with the code that
formats
> my table in the following way?
> 
> Country Variables id year value
> Angola bank_ratio 1 2006 24
> Angola bank_ratio 1 2007 25
> Angola Reserve_ratio 1 2008 77
> Angola Reserve_ratio 1 2009 59
> Angola broad_money 1 2010 163
> Angola broad_money 1 2006 188
> Botswana bank_ratio 2 2006 38
> Botswana bank_ratio 2 2007 34
> Botswana Reserve_ratio 2 2008 64
> Botswana Reserve_ratio 2 2009 65
> Botswana broad_money 2 2010 317
> Botswana broad_money 2 2006 361
> Zimbabwe bank_ratio 3 2006 42
> Zimbabwe bank_ratio 3 2007 49
> Zimbabwe Reserve_ratio 3 2008 57
> Zimbabwe Reserve_ratio 3 2009 86
> Zimbabwe broad_money 3 2010 150
> Zimbabwe broad_money 3 2006 288
> 
> Thank you
> 
> Alternative email: addtarris using icloud.com/TChirume using rbz.co.zw
> Skype: admirechirume
> Call: +263773369884
> whatsapp: +818099861504
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-
> guide.html
> and provide commented, minimal, self-contained, reproducible code.


More information about the R-help mailing list