I need to widen my dataset, so that values from three variables become values for new variables

I have a tibble with four variables:

tibble(a=c(rep("11112", 2), rep("11113", 2)), date=c(as_date("2021-03-01"), as_date("2021-03-15"), as_date("2021-04-01"), as_date("2021-04-15")), valueOne=c(10,20,100,120), valueTwo=c(1,2,10,12))

# A tibble: 4 x 4
  a     date       valueOne valueTwo
  <chr> <date>        <dbl>    <dbl>
1 11112 2021-03-01       10        1
2 11112 2021-03-15       20        2
3 11113 2021-04-01      100       10
4 11113 2021-04-15      120       12

I need to extend this dataset so that I have only one row per value of variable "a" and the other three variables become values for new variables. The desired outcome would look like this:

tibble(a=c("11112", "11113"), dateOne=c(as_date("2021-03-01"), as_date("2021-04-01")), dateOne_valueOne=c(10,100), dateOne_valueTwo=c(1,10), dateTwo = c(as_date("2021-03-15"), as_date("2021-04-15")), dateTwo_valueOne=c(20,120), dateTwo_valueTwo=c(2,12))

# A tibble: 2 x 7
  a     dateOne    dateOne_valueOne dateOne_valueTwo dateTwo    dateTwo_valueOne dateTwo_valueTwo
  <chr> <date>                <dbl>            <dbl> <date>                <dbl>            <dbl>
1 11112 2021-03-01               10                1 2021-03-15               20                2
2 11113 2021-04-01              100               10 2021-04-15              120               12

Pivot data from long to wide — pivot_wider • tidyr (tidyverse.org)

I am no expert with pivot_wider but this is what I would do.

library(tidyr)
library(lubridate)

library(tibble)
library(dplyr)

DF <- tibble(a=c(rep("11112", 2), rep("11113", 2)), 
       date=c(as_date("2021-03-01"), as_date("2021-03-15"), as_date("2021-04-01"), as_date("2021-04-15")), 
       valueOne=c(10,20,100,120), valueTwo=c(1,2,10,12))
DF <- DF %>% group_by(a) %>% mutate(DateSeq = row_number())
DF
#> # A tibble: 4 x 5
#> # Groups:   a [2]
#>   a     date       valueOne valueTwo DateSeq
#>   <chr> <date>        <dbl>    <dbl>   <int>
#> 1 11112 2021-03-01       10        1       1
#> 2 11112 2021-03-15       20        2       2
#> 3 11113 2021-04-01      100       10       1
#> 4 11113 2021-04-15      120       12       2
DF %>% pivot_wider(names_from = DateSeq, values_from = date:valueTwo)
#> # A tibble: 2 x 7
#> # Groups:   a [2]
#>   a     date_1     date_2     valueOne_1 valueOne_2 valueTwo_1 valueTwo_2
#>   <chr> <date>     <date>          <dbl>      <dbl>      <dbl>      <dbl>
#> 1 11112 2021-03-01 2021-03-15         10         20          1          2
#> 2 11113 2021-04-01 2021-04-15        100        120         10         12

Created on 2021-02-23 by the reprex package (v0.3.0)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.