[R] Error:non-numeric argument in my function

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Wed Jun 3 00:38:21 CEST 2009


Stavros Macrakis wrote:
> I agree that it's inconsistent that
>       1:'2'   --> 1:2  # this doesn't seem to be documented in ? seq
>       1+ '2'  --> error
>       1+factor(2)  --> NA (with a warning)
>       1 : factor(4)  --> 1  (uses as.numeric/unclass of factor)
>
>
>   
>> ...i'd expect ...a successful computation (with a character -> numeric
>> coercion of '2' to 2)...
>>
>>     
>
> But I disagree that the best thing to do here is to have them all coerce to
> numerics.  In scripting languages like Perl which are constantly going back
> and forth between internal and external representations, it makes some sense
> to auto-convert numeric strings to numerics and vice versa, but I don't
> think it makes sense in a statistical language.
>
> I would rather see them all give errors.
>   

you're right;  it actually seems to be a *bug* that 1:'2' or '1':2
"successfully" return.  ?':' says:

"The binary operator ':' has two meanings: for factors 'a:b' is
equivalent to 'interaction(a, b)' (but the levels are ordered and
labelled differently).  For numeric arguments 'from:to' is equivalent to
'seq(from, to)', and generates a sequence from 'from' to 'to' in steps
of '1' or '1-'."

but '1' and '2' are neither factors nor numerics, and ':' should have no
meaning for them.

interestingly,

    0i:1
    # 0 1

    '0':1
    # 0 1

i.e., both the complex 0i and the character '0' are successfully (but
undocumentedly) coerced to integers, but

    '0i':1
    # Error in "0i":1 : NA/NaN argument
    # In addition: Warning message:
    # NAs introduced by coercion

while it does not follow from ?':' that the arguments are implicitly
coerced to numerics, it seems a plausible explanation:

    as.numeric(0i)
    # 0
    as.numeric('0')
    # 0
    as.numeric('0i')
    # NA

interestingly,

    as.complex('0i')
    # NA

?as.complex does not explain what sorts of arguments are coercible to
complex, beyond "an object, probably of mode 'complex'".  if as.numeric
can coerce strings to numerics, why can't as.complex do the same for
complex numbers? 

vQ




More information about the R-help mailing list