This question is related to this question dplyr median by group
and has already answers here: pivot_longer with multiple classes causes error ("No common type")
Now I have learned that we should use values_transform instead of values_ptypes.
I want to know what is the reason for this? Is there a deeper reason why values_ptypes does not work and values_transform work now:
Here is the above mentioned example that led me to this problem:
dataframe:
df1 <- data.frame(
Type1 = c("A","A","A", "AB", "AB"),
Type2 = c(1L,2L,2L, 1L, 1L),
Value = c(1L, 2L, 1L, NA, NA),
Median = c(1L, 1.5, 1.5, NA, NA))
Type1 Type2 Value Median
1 A 1 1 1.0
2 A 2 2 1.5
3 A 2 1 1.5
4 AB 1 NA NA
5 AB 1 NA NA
I would like to pivot_longer using values_ptypes argument like this: not working!
library(dplyr)
library(tidyr)
df1 %>%
pivot_longer(
cols = contains("Type"),
names_to = "key",
values_to = "val",
values_ptypes = list(val = 'character')
)
Error: Can't convert <integer> to <character>.
Run `rlang::last_error()` to see where the error occurred.
This should make it possible to combine Type1 and Type2 but it is not working.
I want to know why in this case I can't force type conversion.