Skip to content
Prev 395289 / 398502 Next

Best way to test for numeric digits?

?s 15:59 de 18/10/2023, Leonard Mada via R-help escreveu:
Hello,

If you want to extract chemical elements symbols, the following might work.
It uses the periodic table in GitHub package chemr and a package stringr 
function.


devtools::install_github("paleolimbot/chemr")



split_chem_elements <- function(x) {
   data(pt, package = "chemr", envir = environment())
   el <- pt$symbol[order(nchar(pt$symbol), decreasing = TRUE)]
   pat <- paste(el, collapse = "|")
   stringr::str_extract_all(x, pat)
}

mol <- c("CCl3F", "Li4Al4H16", "CCl2CO2AlPO4SiO4Cl")
split_chem_elements(mol)
#> [[1]]
#> [1] "C"  "Cl" "F"
#>
#> [[2]]
#> [1] "Li" "Al" "H"
#>
#> [[3]]
#>  [1] "C"  "Cl" "C"  "O"  "Al" "P"  "O"  "Si" "O"  "Cl"


It is also possible to rewrite the function without calls to non base 
packages but that will take some more work.

Hope this helps,

Rui Barradas