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!