Search code examples
rtime-seriespivot

time seri from long to wide


I have a data frame like

date. precipitation.
1950-01-01 2.5
1950-01-02 1.5
. .
. .
2021-12-30 1.5
2021-12-31 1

I want to have data frame like this :

year month 1 2 . . 30 31
1950 01 2.5 1.5 . . 3 3.25
1950 02 2 1.7 . . 3.1 3.5
. . . . . . . .
. . . . . . . .
2021 11 2.5 1.5 . . 3 3.25
2021 12 2.3 1.67 . . 1.7 1.5

I would appreciate it if some one could help me. thanks in advance

I extracted month, day, and year in separate columns and use pivot wider:

wide_table <- pivot_wider(df, names_from = day, values_from = value, names_prefix = "Day_", values_fill = NA)

but the result is not exactly the format that I want


Solution

  • For problems like this, split the date up into separate columns first, then use pivot_wider:

    library(tidyverse)
    
    data <- tibble(date = c('1950-01-01', '1950-01-02'),
                   precip = c(2.5, 1.5))
    
    data
    
    date       precip
      <chr>       <dbl>
    1 1950-01-01    2.5
    2 1950-01-02    1.5
    
    data.wide <- data %>% 
      mutate(date = as.Date(date),
             year = year(date),
             month = month(date),
             day = day(date)) %>% 
      select(-date) %>% 
      pivot_wider(names_from = day, values_from = precip)
    
    data.wide
    
    # A tibble: 1 × 4
       year month   `1`   `2`
      <dbl> <dbl> <dbl> <dbl>
    1  1950     1   2.5   1.5
    

    Also, this is a very common and standard problem that has many answers on both this website and others. It's worth developing your searching abilities, especially for usage of basic functions like pivot_wider(). And remember to include example data in your question, not a table, make it easy for your answerers!