Home > database >  Convert a list of characters partially to int
Convert a list of characters partially to int

Time:11-22

I have a list of data:

$nPerm
[1] "1000"

$minGSSize
[1] "10"

$maxGSSize
[1] "100"

$by
[1] "DOSE"

$seed
[1] "TRUE"

This list is supposed to be flexible, so these values could be different and could be something else.

All the data in this list is in character class, the numbers and words also. I would like to know if it is possible to convert only the numbers to numeric, but leave the others as characters/strings.

Thank you in advance!

CodePudding user response:

L <- list(a="1000", b="DOSE", c="99")
type.convert(L, as.is = TRUE)
# $a
# [1] 1000
# $b
# [1] "DOSE"
# $c
# [1] 99

CodePudding user response:

Evan's answer is very neat, just for completeness also a {purrr} option:

L <- list(a="1000", b="DOSE", c="99")
L |> purrr::map(~ifelse(stringr::str_detect(.x,"^[:digit:] $"), as.numeric(.x), .x))
  • Related