Home > Software engineering >  Distinguishing between numeric only strings and otherwise
Distinguishing between numeric only strings and otherwise

Time:03-23

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

CodePudding user response:

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

CodePudding user response:

Here is one base approach using sum() with grepl():

is_num_vec <- function(vec) {
    return(sum(grepl("^\\d (?::\\d )*$", vec)) == length(vec))
}

is_num_vec(A)  # [1] FALSE
is_num_vec(B)  # [1] TRUE

Data:

A <- c("prof2:wcf_type2", "prof2:wcf_type3", "1", "c.f_.")
B <- c("2:2", "2:3", "1", "2")
  • Related