Home > Blockchain >  Changing function-output(y) given value of input(x)
Changing function-output(y) given value of input(x)

Time:02-16

#We know that f(x)=-x^3 if x<=0
#We know that f(x)=x^2 if x:=0-1        
#We know that f(x)=√x if x>1 


x <- 1.5 
print(x)
if(x<=0) { 
  cat("y is",(-x)^3)
} else if(0<x<1) {
  cat("y is", x^2)
} else if(x=>1) { 
  cat("y is", sqrt(x))
}  

New to r. I do not understand why it does not work. Keeps giving me the values of all three functions, and furthermore gives me the error that "unexpected '}' in "}""

Can somebody please help me understand, thanks.

CodePudding user response:

In R, the correct syntax for

  • "x is greater than or equals to 1" is x >= 1
  • "x is smaller than or equals to 1" is x <= 1
  • "x is greater than zero but smaller than 1" is x > 0 & x < 1
x <- 1.5 
print(x)

if(x <= 0) { 
  cat("y is",(-x)^3)
} else if (x > 0 & x < 1) {
  cat("y is", x^2)
} else if(x >= 1) { 
  cat("y is", sqrt(x))
}  

y is 1.224745

If you want to create a function that sort of "calculate y", you can wrap the whole thing in function() {}.

calculate_y <- function(x) {
  if(x <= 0) { 
    cat("y is",(-x)^3)
  } else if (x > 0 & x < 1) {
    cat("y is", x^2)
  } else if(x >= 1) { 
    cat("y is", sqrt(x))
  }  
}

calculate_y(1.5)
y is 1.224745

calculate_y(0.1)
y is 0.01
  •  Tags:  
  • r
  • Related