I would like to pivot it longer using the columns prefixes A and B transfered in a new column named treatment.
But when I try to pivot it longer , I've got the followng error message :
Error in pivot_longer():
! Can't combine A_length and A_chaine
library(tidyr)
library(dplyr)
tableau_2 %>%
pivot_longer(
cols = -c(lot,temp_ID),
names_to = c("treatment", ".value"),
names_sep = "_",
)
#> # A tibble: 4 × 7
#> lot temp_ID treatment length volume weight chaine
#> <dbl> <chr> <chr> <dbl> <dbl> <dbl> <chr>
#> 1 25789 ppp A 45 25 236 bla
#> 2 25789 ppp B 63 569 12 blo
#> 3 24856 ooooo A 25 856 4568 bli
#> 4 24856 ooooo B 47 145 28 blu
In your current attempt you try to fill treatment & measure columns from existing column names and combine numeric and character objects in 3rd column, value . This would work if you'd convert numerics to characters first, but likely it is not what you are after:
tableau_2 %>%
mutate(across(matches("^(A|B)_"), as.character)) %>%
pivot_longer(
cols = -c(lot,temp_ID),
names_to = c("treatment", "measure"),
names_sep = "_",
values_to = "value"
)
#> # A tibble: 16 × 5
#> lot temp_ID treatment measure value
#> <dbl> <chr> <chr> <chr> <chr>
#> 1 25789 ppp A length 45
#> 2 25789 ppp A volume 25
#> 3 25789 ppp A weight 236
#> 4 25789 ppp A chaine bla
#> 5 25789 ppp B length 63
#> 6 25789 ppp B volume 569
#> 7 25789 ppp B weight 12
#> 8 25789 ppp B chaine blo
#> 9 24856 ooooo A length 25
#> 10 24856 ooooo A volume 856
#> 11 24856 ooooo A weight 4568
#> 12 24856 ooooo A chaine bli
#> 13 24856 ooooo B length 47
#> 14 24856 ooooo B volume 145
#> 15 24856 ooooo B weight 28
#> 16 24856 ooooo B chaine blu