Aliases: vector-coercion as_logical as_integer as_double as_complex as_character as_list
Keywords: internal
### ** Examples # Coercing atomic vectors removes attributes with both base R and rlang: x <- structure(TRUE, class = "foo", bar = "baz") as.logical(x)
[1] TRUE
# But coercing lists preserves attributes in base R but not rlang: l <- structure(list(TRUE), class = "foo", bar = "baz") as.list(l)
[[1]] [1] TRUE attr(,"class") [1] "foo" attr(,"bar") [1] "baz"
as_list(l)
Warning: `as_list()` is deprecated as of rlang 0.4.0 Please use `vctrs::vec_cast()` instead. This warning is displayed once every 8 hours.
Warning: `switch_type()` is soft-deprecated as of rlang 0.4.0. Please use `switch(typeof())` or `switch(my_typeof())` instead. This warning is displayed once every 8 hours.
[[1]] [1] TRUE
# Implicit conversions are performed in base R but not rlang: as.logical(l)
[1] TRUE
## Not run: ##D as_logical(l) ## End(Not run) # Conversion methods are bypassed, making the result of the # coercion more predictable: as.list.foo <- function(x) "wrong" as.list(l)
[1] "wrong"
as_list(l)
[[1]] [1] TRUE
# The input is never parsed. E.g. character vectors of numbers are # not converted to numeric types: as.integer("33")
[1] 33
## Not run: ##D as_integer("33") ## End(Not run) # With base R tools there is no way to convert an environment to a # list without either triggering method dispatch, or changing the # original environment. as_list() makes it easy: x <- structure(as_environment(mtcars[1:2]), class = "foobar") as.list.foobar <- function(x) abort("dont call me") as_list(x)
$cyl [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4 $mpg [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4 [16] 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7 [31] 15.0 21.4