'How to switch from Long to Wide format table in R

I am trying to change my data from wide to long format.

It currently looks like this: enter image description here

And I would like it to look like:

enter image description here

This is my current code but does not seem to be working:

gather(parishpop, key= “New_var_name”, value= “var_value”, X2002, X2003, X2004, X2005, X2006, X2007, X2008, X2009, X2010, X2011, X2012, X2013, X2014, X2015, X2016, X2017, X2018, X2019, X2020)

r


Solution 1:[1]

library(data.table)
setDT(df)

# wide to long
melt(df
     , id.vars = "i..Parish"
     , measure.vars = patterns("^X")
     , variable.name = 'Year'
     , value.name = "Population"
     )[, Year := gsub('X', '', Year)][]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AndrewGB