Have I Correctly Used Pivot_Wider Here?

I have this dataset:

my_data = structure(list(col = c("A", "B", "C"), `2000-01-01` = c(86L, 
43L, 73L), `2000-01-02` = c(99L, 77L, 12L)), class = "data.frame", row.names = c(NA, 
-3L))

  col 2000-01-01 2000-01-02
1   A         86         99
2   B         43         77
3   C         73         12

My goal is to transform this dataset into the following format:

        date col count
1 2000-01-01   A    86
2 2000-01-01   B    43
3 2000-01-01   C    73
4 2000-01-02   A    99
5 2000-01-02   B    77
6 2000-01-02   C    12

Have I done this correctly?

# how come this seems to works for all columns even though I only specified "2001-01-01"?
my_data %>%
  pivot_longer(!col, names_to = "2001-01-01", values_to = "count")

# A tibble: 6 x 3
  col   `2001-01-01` count
  <chr> <chr>        <int>
1 A     2000-01-01      86
2 A     2000-01-02      99
3 B     2000-01-01      43
4 B     2000-01-02      77
5 C     2000-01-01      73
6 C     2000-01-02      12

Thanks!

I would set names_to = "DATE" or some other descriptive name and not to a date-like string, but the code is otherwise fine.

1 Like

@ FJCC: Thank you for your reply!

I tried your suggestion:

my_data %>% pivot_longer(!col, names_to = "DATE", values_to = "count")

But this gives me the following error:

Error in `chr_as_locations()`:
! Can't subset columns that don't exist.
x Column `col` doesn't exist.
Run `rlang::last_error()` to see where the error occurred.

Have I done this correctly?
Thanks!

Here is what I get:

library(tidyr)
my_data = structure(list(col = c("A", "B", "C"), 
                         `2000-01-01` = c(86L, 43L, 73L), 
                         `2000-01-02` = c(99L, 77L, 12L)), class = "data.frame", row.names = c(NA, -3L))
my_data %>% pivot_longer(!col, names_to = "DATE", values_to = "count")
#> # A tibble: 6 × 3
#>   col   DATE       count
#>   <chr> <chr>      <int>
#> 1 A     2000-01-01    86
#> 2 A     2000-01-02    99
#> 3 B     2000-01-01    43
#> 4 B     2000-01-02    77
#> 5 C     2000-01-01    73
#> 6 C     2000-01-02    12

Created on 2022-12-09 with reprex v2.0.2

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