Home > Software design >  Cast multiple values in R
Cast multiple values in R

Time:10-28

Is there a way to cast multiple values in R

asd <- data.frame(week = c(1,1,2,2), year = c("2019","2020","2019","2020"), val = c(1,2,3,4), cap = c(3,4,6,7))

Expected output

week 2019_val 2020_val 2019_cap 2020_cap
1        1       2        3        6 
2        3       4        4        7

CodePudding user response:

With tidyr::pivot_wider you could do:

asd <- data.frame(week = c(1,1,2,2), year = c("2019","2020","2019","2020"), val = c(1,2,3,4), cap = c(3,4,6,7))

tidyr::pivot_wider(asd, names_from = year, values_from = c(val, cap), names_glue = "{year}_{.value}")
#> # A tibble: 2 × 5
#>    week `2019_val` `2020_val` `2019_cap` `2020_cap`
#>   <dbl>      <dbl>      <dbl>      <dbl>      <dbl>
#> 1     1          1          2          3          4
#> 2     2          3          4          6          7

CodePudding user response:

If you want to do this in base R, you can use reshape:

reshape(asd, direction = "wide", idvar = "week", timevar = "year", sep = "_")
#>   week val_2019 cap_2019 val_2020 cap_2020
#> 1    1        1        3        2        4
#> 3    2        3        6        4        7

Note that it is best not to start your new column names with the year, since variable names beginning with numbers are not legal in R, and therefore always need to be quoted. It becomes quite tiresome to write asd$'2020_val' rather than asd$val_2020 and can often lead to errors when one forgets the quotes.

  • Related