1

How do I reshape this wide data: (from a csv file)

Name    Code    Indicator     1960    1961    1962  

Into this long format?

Name    Code    Indicator     Year
lmo
  • 37,904
  • 9
  • 56
  • 69
dani
  • 4,880
  • 8
  • 55
  • 95

3 Answers3

7

the reshape2 package does this nicely with the function melt.

yourdata_melted <- melt(yourdata, id.vars=c('Name', 'Code', 'Indicator'), variable.name='Year')

This will add a column of value that you can drop. yourdata_melted$value <- NULL

Justin
  • 42,475
  • 9
  • 93
  • 111
5

And just because I like to continue my campaign for using base R functions:

Test data:

test <- data.frame(matrix(1:12,nrow=2))
names(test) <- c("name","code","indicator","1960","1961","1962")
test

  name code indicator 1960 1961 1962
1    1    3         5    7    9   11
2    2    4         6    8   10   12

Now reshape it!

reshape(
   test,
   idvar=c("name","code","indicator"),
   varying=c("1960","1961","1962"),
   timevar="year",
   v.names="value",
   times=c("1960","1961","1962"),
   direction="long"
)

#           name code indicator year value
#1.3.5.1960    1    3         5 1960     7
#2.4.6.1960    2    4         6 1960     8
#1.3.5.1961    1    3         5 1961     9
#2.4.6.1961    2    4         6 1961    10
#1.3.5.1962    1    3         5 1962    11
#2.4.6.1962    2    4         6 1962    12
thelatemail
  • 91,185
  • 12
  • 128
  • 188
  • I also try to campaign for base R `reshape`--its fast and not too difficult to use after you've used it a few times--but it seems like the functions in the "reshape2" package are the only ones that get any love. – A5C1D2H2I1M1N2O1R2T1 Dec 14 '12 at 04:18
  • Plus 1 for the sheer lol of going to the effort just to campaign for base R functions. – Chris Beeley Dec 16 '12 at 19:37
1

With tidyr

gather(test, "time", "value", 4:6)

Data

test <- data.frame(matrix(1:12,nrow=2))
names(test) <- c("name","code","indicator","1960","1961","1962")
Pierre L
  • 28,203
  • 6
  • 47
  • 69