Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reshape long to wide with multiple variables

I have a long df in R that looks like this:

structure(list(pta = c("636", "899", "989", "1007", "561"), cafta_similarity = c(0.81468368791454, 
0.68814557488039, 0.96371483934995, 0.71527668922595, 0.69435303348955
), iso3n = c(124, 124, 124, 124, 152), ccode = c(20, 20, 20, 
20, 155), country = c("Canada", "Canada", "Canada", "Canada", 
"Chile"), year = c("1992", "2016", "2018", "2018", "1960"), gdppc = c(20879.8483300891, 
42315.6037056806, 46548.6384108296, 46548.6384108296, 505.349325487754
), polity2 = c(10, 10, 10, 10, 5), openness = c(52.7380309449972, 
65.3636199818813, 66.5818530921921, 66.5818530921921, 46.9745037862152
), hog_right = c(3, 0, 0, 0, 3), hog_left = c(0L, 1L, 1L, 1L, 
0L), hog_center = c(0, 0, 0, 0, 0)), class = c("data.table", 
"data.frame"), row.names = c(NA, -5L), .internal.selfref = <pointer: 0x7fca56811ae0>)

What I am trying to do is to get it wide across all variables so that I can compute averages on a dyadic level. Basically what I want is pta.1, pta.2, iso3n.1, iso3n.2 and etc… Does anyone know how I can do this?

I have looked at most answers here on reshaping data and tried some but nothing seems to work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Perhaps this helps

library(data.table)
dcast(df, country + year ~ rowid(country, year), value.var = c("pta", "iso3n"), sep = ".")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading