Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Distinguishing between numeric only strings and otherwise

I want to make a logical test to distinguish between string vectors that except ":" are made of only numbers (like vector B) AND string vectors that except ":" are NOT made of only numbers (like vector A).

The name of this logical test can be is_num_vec (see below). Is this possible in R?

A = c("prof2:wcf_type2", "prof2:wcf_type3", "1", "c.f_.")
B = c("2:2", "2:3", "1", "2")


is_num_vec <- function(vec){

# Your solution

}

#### EXPECTED OUTPUT:
 is_num_vec(A)
> [1]  FALSE

 is_num_vec(B)
> [1]  TRUE

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here is a very simple solution that might fit your purpose:

First remove : from vec, then use grepl() to test whether all elements in vec are numbers only ^[0-9]{1,}$. Use all() to test whether all logical values are TRUE.

is_num_vec <- function(vec){
  all(grepl("^[0-9]{1,}$", gsub(":", "", vec)))
}

is_num_vec(A)
[1] FALSE

is_num_vec(B)
[1] TRUE

is_num_vec("5a3")
[1] FALSE
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading