Home > other >  What is causing this error in my piecewise function in R?
What is causing this error in my piecewise function in R?

Time:06-30

I'm trying to make a piecewise function in R with the following arguments:

##### Rules ####

# If x from 2 to 6, x2
# If x < 2, x-5
# If x > 6, x^9

Thus, I have made this function to try to fit these arguments:

piecewise <- function(x){
  return(ifelse(x < 2, x - 5,
                ifelse(x > 6, x^9, x^2)))
}

I created a vector to test this out and fit it into the function:

x <- c(1,20,5,2,30)
piecewise(x)

However, it gives me the following odd output:

[1] -4.0000e 00  5.1200e 11  2.5000e 01  4.0000e 00  1.9683e 13

What is causing this issue and how do I fix it?

CodePudding user response:

You can change R's print options for scientific notation by setting the scipen "scientific notation penalty" option. Numbers with fewer digits than scipen will be printed without scientific notation:

options(scipen = 35)
x <- c(1,20,5,2,30)
piecewise(x)
# [1]             -4   512000000000             25              4 19683000000000

See ?options for more details.

  • Related