[R] If (x > 0)
jim holtman
jholtman at gmail.com
Tue Feb 14 01:05:32 CET 2012
Seems to work fine for me:
> conditional1 <- function(x){
+ result <- 0
+ if (x > 0) {
+ result <- 1
+ } else if (x < 0) {
+ result <- -1
+ }
+ return(result)
+ }
> conditional1(-1)
[1] -1
> conditional1(1)
[1] 1
> conditional1(0)
[1] 0
>
On Mon, Feb 13, 2012 at 4:59 PM, Schmidt, Michael
<MSchmidt at med.miami.edu> wrote:
> Hi,
> I am new to R. I was trying to get a very simple program to run. Take one number from the command line. If the number < 0 return -1. If number > 0 return 1 and if the number == 0 return 0. The code is in a file called test1.R
>
>
> The code:
>
> #useage: R --no-save --args 5 < test1.R
> args = (commandArgs(TRUE))
> x = as.numeric(args[1])
> print(x)
>
> res <- conditional1(x)
> cat("result= ",res,"\n")
>
> conditional1 <- function(x){
> result <- 0
> if (x > 0) {
> result <- 1
> } else if (x < 0) {
> result <- -1
> }
> return(result)
> }
>
>
> The output:
>>R --no-save --slave --args 1 < test1.R
> [1] 1
> result= 1
>>R --no-save --slave --args -1 < test1.R
> [1] -1
> result= -1
>>] R --no-save --slave --args 0 < test1.R
> [1] 0
> result= -1
>
>
> The problem:
> For arguments 1 and -1 it works as intended. For 0 (zero) it does not. If the 0 value is passed into the function named "conditional1" I would expect both if-statements to evaluate to false and 0 being return. From what I can tell (0 < 0) evaluates to true since -1 is returned. Hmmmmm...
> What is going on? What am I doing wrong? Why is this happening? I am baffled!
> Any help would be appreciated.
> Thanks
> Mike
>
>
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
--
Jim Holtman
Data Munger Guru
What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.
More information about the R-help
mailing list