r-lib / vctrs

Generic programming with typed R vectors
https://vctrs.r-lib.org
Other
287 stars 66 forks source link

Inconsistent handling of NA in `vec_cast()` #1912

Open pbrohan opened 7 months ago

pbrohan commented 7 months ago

vec_cast() seems to successfully cast non-logical NAs using the defined vec_cast() functions, (e.g. NA_integer will be cast using the same function as 3L), however logical NA (NA) does not use the defined function for booleans, and instead replaces the vector data with NA, side-stepping the casting functions.

library(vctrs)
new_reprex <- function(x = 1){
    new_rcrd(list(a = x, b = as.integer(x)), class = "reprex")
}

format.reprex <- function(x, ...) vec_data(x)

vec_cast.reprex.logical <- function(x, to, ...) "I was logical"
vec_cast.reprex.integer <- function(x, to, ...) "I was an integer"

vec_cast(3L, new_reprex())
#> [1] "I was an integer"

vec_cast(NA_integer_, new_reprex())
#> [1] "I was an integer"

vec_cast(FALSE, new_reprex())
#> [1] "I was logical"

vec_cast(NA, new_reprex())
#> <reprex[1]>
#>        
#> 1 NA NA

Created on 2024-02-19 with reprex v2.1.0.9000