How can I 'unpivot' a table? What is the proper technical term for this?
UPDATE: The term is called melt
I have a data frame for countries and data for each year
Country 2001 2002 2003
Nigeria 1 2 3
UK 2 NA 1
And I want to have something like
Country Year Value
Nigeria 2001 1
Nigeria 2002 2
Nigeria 2003 3
UK 2001 2
UK 2002 NA
UK 2003 1
You can use the
melt
command from thereshape
package. See here: http://www.statmethods.net/management/reshape.htmlProbably something like
melt(myframe, id=c('Country'))
The base R
reshape
approach for this problem is pretty ugly, particularly since the names aren't in a form thatreshape
likes. It would be something like the following, where the firstsetNames
line modifies the column names into something thatreshape
can make use of.A better alternative in base R is to use
stack
, like this:There are also new tools for reshaping data now available, like the "tidyr" package, which gives us
gather
. Of course, thetidyr:::gather_.data.frame
method just callsreshape2::melt
, so this part of my answer doesn't necessarily add much except introduce the newer syntax that you might be encountering in the Hadleyverse.All three options here would need reordering of rows if you want the row order you showed in your question.
A fourth option would be to use
merged.stack
from my "splitstackshape" package. Like base R'sreshape
, you'll need to modify the column names to something that includes a "variable" and "time" indicator.Sample data
I still can't believe I beat Andrie with an answer. :)