Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coerce arguments to simplest type

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"
like image 428
Moody_Mudskipper Avatar asked Nov 02 '25 03:11

Moody_Mudskipper


1 Answers

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
like image 179
Ronak Shah Avatar answered Nov 03 '25 20:11

Ronak Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!