Home > Back-end >  Continuous function in R Programming
Continuous function in R Programming

Time:09-26

I'm trying to code the following continuous function in R Programming.

This is an image of my f(x)

I was trying to create a function called fun1 that takes a single argument vecA. I want the function to return the values of f(x) evaluated at the values of vecA.

fun1(vecA) <- function(x){
   x^2 2x 3
 }

I don't know how I can continue it.

CodePudding user response:

Ideally your function should be able to take vectorized input, in which case you should use ifelse or case_when.

For example:

f <- function(x) {
  ifelse(x < 0, x^2   2*x   3,
         ifelse(x >= 2, x^2   4 * x - 7,
                x   3))
}

Or

f <- function(x) {
  dplyr::case_when(x < 0 ~ x^2   2*x   3,
                   x > 2 ~ x^2   4 * x - 7,
                   TRUE  ~ x   3)
}

both of which produce the same output. We can see what the function looks like by doing:

plot(f, xlim = c(-5, 5))

Created on 2022-09-25 with reprex v2.0.2

CodePudding user response:

Try studying the patterns here:

fun1 <- function(x){
   if (x < 0) {
     x^2 2*x 3
   } else if (x < 2) {
     x   3
   } else {
     # Your turn
   }
}
  • Related