I am trying to solve this problem with the r language. But I didn't get the answer I expected. My code return -5, while the correct return should be -5, 0, 0, 0, 5. I think my code didn't go through everything in the input_vector. How can i fix it?


I am trying to solve this problem with the r language. But I didn't get the answer I expected. My code return -5, while the correct return should be -5, 0, 0, 0, 5. I think my code didn't go through everything in the input_vector. How can i fix it?


It doesn't need any loop i.e.
lambda <- 4
ifelse(abs(v1) > lambda, v1, 0)
[1] -5 0 0 0 5
Or simply multiply by the logical vector (TRUE -> 1 and FALSE -> 0)
v1 * (abs(v1) > lambda)
[1] -5 0 0 0 5
But, if the intention is to use for loop, create a output vector to collect the output and return once at the end
sign.function <- function(input_vector) {
out <- numeric(length(input_vector))
for(i in seq_along(input_vector)) {
if(abs(input_vector[i]) > lambda) {
out[i] <- input_vector[i]
}
}
return(out)
}
> sign.function(v1)
[1] -5 0 0 0 5
v1 <- c(-5, -3, 0, 3, 5)