[R] tidyr gather(function)

reichm@@j m@iii@g oii sbcgiob@i@@et reichm@@j m@iii@g oii sbcgiob@i@@et
Tue Jul 16 00:47:21 CEST 2019


r-help

 

Needing to transform some data for a time series (1930 - 2018). 

 

> tempDat
# A tibble: 89 x 13
    Year   Jan   Feb   Mar   Apr   May   Jun   Jul   Aug   Sep   Oct   Nov
Dec
   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
<dbl>
 1  1930  52    60.3  60.6  72.2  71.7  86.8  91.3  89.7  82.3  70.4  60.2
52.2
 2  1931  52.9  57.8  62.7  72.4  80.5  87    95.1  89.3  85.9  72.8  57.2
49.7
 3  1932  47    56.8  61.9  69.3  77.2  84.7  91.9  92.1  87    71.5  62.9
49.3
 
If I use the gather function:

 

tempDat.long <- gather(data=tempDat, key=month, value=temp, "Jan", "Feb",
"Mar",

 
"Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")

 

> tempDat.long
# A tibble: 1,068 x 3
    Year month  temp
   <dbl> <chr> <dbl>
 1  1930 Jan    52  
 2  1931 Jan    52.9
 3  1932 Jan    47  
 4  1933 Jan    48.8
 5  1934 Jan    54.5

 

But I need it to be 

 

    Year month  temp
   <dbl> <chr> <dbl>
 1  1930 Jan    xx.x  
 2  1930 Feb    xx.x
 3  1930 Mar    xx.x
 4  1930 Apr    xx.x
 5  1930 May    xx.x

 

So would I need to use the lubridate package to rearrange my data or is
there a more straight forward method?

 

 

Jeff Reichman


	[[alternative HTML version deleted]]



More information about the R-help mailing list