Home > Software engineering >  Reshape long to wide with multiple variables
Reshape long to wide with multiple variables

Time:10-13

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.

CodePudding user response:

Perhaps this helps

library(data.table)
dcast(df, country   year ~ rowid(country, year), value.var = c("pta", "iso3n"), sep = ".")
  • Related