Creating a function with if and else

Good Morning, I am an italian student and I have an exam the next week on R coding and I really don’t know how to solve this exercise.

I have to write a function, that has as input a vector v and that produce as output the number of components greater than 0.

So that, if i write a vector x ← c(1,1,5,-1,-1,-1), f (x) should give me only the components of the vectors that are greater than 0.

Thank you in advance, I hope someone will help me.

Hello Martino Dalla Vecchia,

Here is an example of a function in R that takes a vector as input and returns the components of the vector that are greater than 0:

f <- function(v) {
  result <- v[v > 0]
  return(result)
}

You can then call the function with your example vector:

x <- c(1, 1, 5, -1, -1, -1)
f(x)

This will return a new vector containing only the components of the input vector x that are greater than 0. In this case, the output will be [1,1,5] It means the function is returning the components of the vector which are greater than 0 in the input vector.

Using if-else Statement

f <- function(v) {
  result <- c()
  for (i in v) {
    if (i > 0) {
      result <- c(result, i)
    }
  }
  return(result)
}

You can then call the function with your example vector:

x <- c(1, 1, 5, -1, -1, -1)
f(x)

In this function instead of using v[v > 0] which is a more concise way, I am using the for loop and if-else statement to check each component of the vector if it is greater than 0, if yes then adding it to new vector called result.

I hope the solution I provided was helpful. If you have any more questions or concerns please let me know!

1 Like