Check complex

Create issue
Issue #5 new
Guillaume Blanchet created an issue

By and odd turn of event, I was looking for a way to check for complex number in a string of characters.

After taking a quick look at the check.numeric function in the varhandle package I found that checking for complex number can be done by modifying the regex_patternobject to


The down side of this modification is that it will find a complex as well as a numeric.

In any case, I thought this would be worth mentioning (and potentially including) to the varhandle package.

Guillaume Blanchet Université de Sherbrooke

Comments (2)

  1. Mehrad Mahmoudian repo owner

    Thank you for taking time and posting this here. I agree that this is a potential improvement, but there is a catch. In the documentation of check.numeric we currently have:

    This function gets a character or factor vector and checks if all the value can be safely converted to numeric.

    This means that in primitive usage, you should be able to do the following without error or warning:

    > a <- c("12", "+2", ".3", "12b", "0.01")
    > check.numeric(a)
    > as.numeric(a[check.numeric(a)])
    [1] 12.00  2.00  0.30  0.01

    But having a complex number changes the behavior (warning will be produced when as.numeric is used over a string of complex number):

    > a <- c("12", "+2", "3i", "12b", "0.01")
    > as.numeric(a)
    [1] 12.00  2.00    NA    NA  0.01
    Warning message:
    NAs introduced by coercion

    So I have a proposal: how about having an argument named match.complex which is FALSE by default but it can be set as true

    Here is my understanding of the situation:

    >  a <- 3i
    >  class(a)
    [1] "complex"
    > is.numeric(a)
    [1] FALSE
    > a-1
    [1] -1+3i

    Therefore the regular expression for matching complex numbers can be added as an optional argument. Does this satisfy your needs?

  2. Guillaume Blanchet reporter

    I did not have any specific as to how to use this bit of code (or the details of how to include it) except that I thought it would be useful to have this bit of code in your package because it is the place I found it would be the best for it.

    In other words, I just shared a bit of code I though would be useful for someone.

    The way to implement this in your package is up to you. Personally, I think your idea to have a match.complex argument in the function is a good one.

  3. Log in to comment