0

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.

0

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.