from long to wide format in data frames

Hi,

I have the following dataset:

  city period gasprice houseprice
1    1   2020 1.324549   183661.6
2    2   2020 2.197691   193749.0
3    3   2020 3.808314   193965.1
4    1   2021 2.455753   194041.6
5    2   2021 1.776679   196797.6
6    3   2021 2.384569   198689.6

I would like this dataset to be like this:

  city  gasprice_2020   houseprice_2020     gasprice_2021    houseprice_2021
1    1      1.324549       183661.6         2,4555753          194041.6
2    2      2.197691       193749.0         1.776679            196797.6
3    3     3.808314        193965.1         2.384569            198689.6

Would be nice if someone knew how to solve this.

library(tidyverse)
df <- tibble(
  city = rep(1:3, 2), 
  period = c(rep(2020, 3), rep(2021, 3)), 
  gasprice = runif(6), 
  houseprice = runif(6)
)
df
#> # A tibble: 6 x 4
#>    city period gasprice houseprice
#>   <int>  <dbl>    <dbl>      <dbl>
#> 1     1   2020   0.755      0.376 
#> 2     2   2020   0.649      0.0633
#> 3     3   2020   0.337      0.839 
#> 4     1   2021   0.0358     0.589 
#> 5     2   2021   0.254      0.0479
#> 6     3   2021   0.934      0.450
df %>% pivot_wider(id_cols = city, names_from = period, values_from = c(gasprice, houseprice))
#> # A tibble: 3 x 5
#>    city gasprice_2020 gasprice_2021 houseprice_2020 houseprice_2021
#>   <int>         <dbl>         <dbl>           <dbl>           <dbl>
#> 1     1         0.755        0.0358          0.376           0.589 
#> 2     2         0.649        0.254           0.0633          0.0479
#> 3     3         0.337        0.934           0.839           0.450

Created on 2021-06-16 by the reprex package (v1.0.0)

1 Like

Thanks for the response.

When I run the code I get "Error in pivot_wider(....) :
could not find function "pivot_wider"

Do you know how to solve this?

This message indicates that you omitted

library(tidyverse)

This topic was automatically closed 21 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.