pivot_longer: values_ptypes: 无法将 <integer> 转换为 <character>

pivot_longer: values_ptypes: can't convert <integer> to <character>

这个问题与这个问题相关

并且已经在这里回答:

现在我知道我们应该使用values_transform而不是values_ptypes

我想知道这是什么原因? values_ptypes 不起作用而 values_transform 现在起作用是否有更深层次的原因:

这是导致我遇到此问题的上述示例:

数据框:

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

我想pivot_longer使用这样的values_ptypes参数:不工作!

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.

这应该可以组合 Type1Type2,但它不起作用。

我想知道为什么在这种情况下我不能强制类型转换。

pivot_longer 需要重塑列以具有相同的类型。这里'Type1'和'Type2'在class中是不同的。通过在 values_transform 中转换为 character 将其更改为单个 class。根据?pivot_longer

names_ptypes, values_ptypes - A list of column name-prototype pairs. A prototype (or ptype for short) is a zero-length vector (like integer() or numeric()) that defines the type, class, and attributes of a vector. Use these arguments if you want to confirm that the created columns are the types that you expect. Note that if you want to change (instead of confirm) the types of specific columns, you should use names_transform or values_transform instead.

library(dplyr)
library(tidyr)
df1 %>% 
   pivot_longer(
     cols = contains("Type"),
     names_to = "key",
     values_to = "val", 
     values_transform = list(val = as.character))

-输出

# A tibble: 10 × 4
   Value Median key   val  
   <int>  <dbl> <chr> <chr>
 1     1    1   Type1 A    
 2     1    1   Type2 1    
 3     2    1.5 Type1 A    
 4     2    1.5 Type2 2    
 5     1    1.5 Type1 A    
 6     1    1.5 Type2 2    
 7    NA   NA   Type1 AB   
 8    NA   NA   Type2 1    
 9    NA   NA   Type1 AB   
10    NA   NA   Type2 1    

pivot_longer 调用 pivot_longer_spec 并且在函数内下面的行生成错误

Browse[2]> 
debug: out <- vec_c(!!!val_cols, .ptype = val_type)
Browse[2]> 
Error: Can't convert <integer> to <character>.
Run `rlang::last_error()` to see where the error occurred.