I have a data.frame xthat looks like this:
date x1 x2 x3
1    11 21 31
2    12 22 32
3    13 23 33
But I want to efficiently change it to look like this:
date product amount
1    x1       11
1    x2       21
...  
How can I do this in R?
I have a data.frame xthat looks like this:
date x1 x2 x3
1    11 21 31
2    12 22 32
3    13 23 33
But I want to efficiently change it to look like this:
date product amount
1    x1       11
1    x2       21
...  
How can I do this in R?
 
    
    You can do:
tidyr::pivot_longer(df, -1)
#> # A tibble: 9 x 3
#>    date name  value
#>   <int> <chr> <int>
#> 1     1 x1       11
#> 2     1 x2       21
#> 3     1 x3       31
#> 4     2 x1       12
#> 5     2 x2       22
#> 6     2 x3       32
#> 7     3 x1       13
#> 8     3 x2       23
#> 9     3 x3       33
Data
df <- structure(list(date = 1:3, x1 = 11:13, x2 = 21:23, x3 = 31:33), 
class = "data.frame", row.names = c(NA, -3L))
df
#>   date x1 x2 x3
#> 1    1 11 21 31
#> 2    2 12 22 32
#> 3    3 13 23 33
