Quantizer
Quantizer

Reputation: 297

Create functions in R

I'm fairly new to R and I have not been working with functions in R before. I want to write a program/algorithm (using R) that calculates the square root of a given positive number. Would anyone mind take the time to give me an example of how this can be achieved?

Thanks a lot in advance!

UPDATE

 posNum_to_squaRtNum <- function(posNum) {
if (posNum <= 0)
  print("Due to mathmatical principles you have to input a positive number")
else
  squaRtNum <- sqrt(posNum)
  return(squaRtNum)

}

When I insert a negative number in the function, the output is my print PLUS the error: "Error in posNum_to_squaRtNum(-1) : object 'squaRtNum' not found." It should not go on to the else statement, if the if statement is fulfilled right?

Upvotes: 0

Views: 52

Answers (1)

SteveM
SteveM

Reputation: 2301

You should wrap your if conditions in brackets:

posNum_to_squaRtNum <- function(posNum) {
  if (posNum <= 0) {
    print("Due to mathmatical principles you have to input a positive number")
 } else {
    squaRtNum <- sqrt(posNum)
  return(squaRtNum)
  }  
}

Upvotes: 1

Related Questions