When dealing with user input using packages shiny or plumber one often needs to convert character arguments to numeric or logical.
I would like to do it automatically, what's an efficient way to do it ?
expected (this or similar) :
convert_args <- ...
fun <- function(a, b, c, d){
convert_args()
dplyr::lst(a, b, c , d)
}
fun("na","true","1","foo")
#> $a
#> [1] NA
#>
#> $b
#> [1] TRUE
#>
#> $c
#> [1] 1
#>
#> $d
#> [1] "foo"
One option is to use readr::parse_guess which as the name suggests tries to guess the type of the character vector.
convert_args <- function(x) {
lapply(x, readr::parse_guess)
}
convert_args(c("NA","true","1","foo"))
#[[1]]
#[1] NA
#[[2]]
#[1] TRUE
#[[3]]
#[1] 1
#[[4]]
#[1] "foo"
This doesn't directly work when we have "na"
readr::parse_guess("na")
#[1] "na"
but as @Moody_Mudskipper mentions it can be resolved specifying na argument in parse_guess
readr::parse_guess("na", c("na", "NA"))
#[1] NA
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With