1

I have a long dataset like this:

 Currency Year  Percentage
  <chr>    <chr>      <dbl>
1 PEN      2009       0.630
2 PEN      2010       0.584
3 PEN      2011       0.618
4 PEN      2012       1.03 
5 PEN      2013       1.00 
6 PEN      2014       1.05 

and I would like to reshape it into wide direction such that currency is the time variable.

reshape(peru, direction = "wide", idvar = "Year", v.names =  "Percentage",
               timevar = "Currency")

But this code got me:

Year  `Percentage.c("PEN", "USD", "EURO", "Other")`
   <chr>                                         <dbl>
 1 2009                                             NA
 2 2010                                             NA
 3 2011                                             NA
 4 2012                                             NA
 5 2013                                             NA
 6 2014                                             NA

Why did everything change into NA and why is my time variable not separated into "PEN", "USD", "EURO" and "Other"? I was expecting there to be 4 different variables: Percentage.PEN, Percentage.EURO, Percentage.USD and Percentage.Other.

thelatemail
  • 91,185
  • 12
  • 128
  • 188
Rainroad
  • 191
  • 8
  • 3
    The problem is that you are working with a `tibble` and not a plain old `data.frame`, which are *not* 100% interchangeable. The `reshape` code looks fine - try `reshape(as.data.frame(peru)...` and it will be okay. Or alternatively use the *tidyr* package for reshaping which will play more nicely with the tidyverse-designed objects. – thelatemail Aug 19 '19 at 22:10
  • Similar to this previous issue - https://stackoverflow.com/questions/43228109/problems-converting-from-wide-to-long-using-reshape-tibble-issue and is a long-acknowledged issue on github - https://github.com/tidyverse/tibble/issues/231 – thelatemail Aug 19 '19 at 22:35

1 Answers1

0

Here's a tidyr example

library(tidyverse)
x <- tribble(~currency, ~year, ~percentage,
        'PEN', 2009, 0.63,
        'PEN', 2010, 1.03,
        'USD', 2009, 0.63,
        'USD', 2010, 1.03,
        'EURO', 2009, 0.63,
        'EURO', 2010, 1.03)

x %>% tidyr::spread(currency, percentage)
# # A tibble: 2 x 4
#     year  EURO   PEN   USD
# <dbl> <dbl> <dbl> <dbl>
# 1  2009  0.63  0.63  0.63
# 2  2010  1.03  1.03  1.03
Tony Ladson
  • 3,539
  • 1
  • 23
  • 30