-2

I have to create a function which will detect if there is any non numeric value present in input. For this I have written this code

test<-function(x){
  if(is.numeric(x)){
    return(T)
  }else{
    return(F)
  }
}

However when I test it with say

> test(a123)
Error in test(a123) : object 'a123' not found

But it works when i use quotes

> test("a123")
[1] FALSE

However I want it working in the first form. Any help on this will be greatly appreciated

Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
Rajarshi Bhadra
  • 1,826
  • 6
  • 25
  • 41
  • Use ```exists()``` in conjuction with your function: http://stackoverflow.com/questions/9368900/how-to-check-if-object-variable-is-defined-in-r – edin-m Dec 15 '15 at 07:43
  • 3
    That are two different things: the string "a123" and the object with the name **a123**. BTW: Why do you write this function if it does the same as `as.numeric()` ? – jogo Dec 15 '15 at 07:45
  • Its just for validating if while entering values in code one has mistakenly included a symbol or an alphabet – Rajarshi Bhadra Dec 15 '15 at 07:46
  • I think what if you want to detect if there are *numeric* symbols in a *character*, you need a regular expression. – Vongo Dec 15 '15 at 07:50
  • Yes. The objective is to detect if there are numeric symbols or characters mistakenly typed in while typing in numbers – Rajarshi Bhadra Dec 15 '15 at 07:52
  • 1
    Try `x <- deparse(substitute(x))` in your function ? – jMathew Dec 15 '15 at 08:12

1 Answers1

0

test(a123) will not work. You have to store the user input in a object first and then pass it to your function.

Note that with your function test(123) also returns FALSE! (even if you insert deparse(substitute(x)) as suggested in the comments)

A shorter and correct way to perform your test is grep("[^0-9]", x) that returns 1 if the string x contains anything that is not a digit, 0 if not.

If you really want to have your function to work in what you refer to as the 1st form (but I think it is not a good idea as it can't receive any object and doesn't seem to have any use in an R script) :

test<-function(x){
  x<-deparse(substitute(x))
  grep("[^0-9]",x)
}

> test(123)
integer(0)
> test(a123)
[1] 1
GPierre
  • 893
  • 9
  • 25
  • The `grep` test should have `-`, `.` and `e` within the character class squeare-brackets to allow for decimals and scientific notation. – IRTFM Dec 15 '15 at 18:08