Sverdo
Sverdo

Reputation: 15

Why am I getting unexpected input error for this function in R?

I want the function to return the fahrenheit to celcius equation if I type in for instance, c, 2) and the other way around if I i type in f instead. This is the function I have:


Temperatureconverter <- function(v,x){
  x = 0
  if(v == c) {          
    return(x*9/5+32)
  if(v == f){             
    return((x−32)×5/9)
  }}

And this is the error:

Error in source("~/Documents/MAE4000/R/test.R", echo = TRUE) : 
  ~/Documents/MAE4000/R/test.R:7:14: unexpected input
6:   if(v == f){             
7:     return((x−
                ^

Upvotes: 0

Views: 432

Answers (1)

Fernando Barbosa
Fernando Barbosa

Reputation: 1134

I rewrote the code as below to solve all the missing details:

Temperatureconverter <- function(v,x)
{
  if(v == "c") return(x*9/5+32)
  if(v == "f") return((x-32)*5/9)
  else return ("Please enter c for Celsius or f for Fahrenheit")
}

Temperatureconverter("f",100) # calling the function 

The comments are right:

  • Setting x to zero after receiving a value for x made the calculation wrong
  • The 'minus' was not the proper symbol
  • Multiplication should always be *.

Upvotes: 2

Related Questions