-3

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? enter image description here

enter image description here

ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
  • 2
    Welcome to Stackoverflow. Since you'll be visiting often, in addition to @akrun comment/answers below, learn to love `debug(my_new_function)` or `debugonce(my_new_function)`, the letters `s`, `n`, `c`, and the function`ls()`, that allow you to track intermediate results of a function, for loop, etc, to see if things are going as you expect. Additionally, in debug, you can experiment with different code at different steps to see if they might serve better than what you have. It will save you a lot of time. – Chris Apr 10 '22 at 21:26
  • 2
    Also please don't share screenshots - instead, copy and paste the actual code. This makes it more likely for you to find help. See [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Andrea M Apr 10 '22 at 21:42

1 Answers1

2

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

data

v1 <- c(-5, -3, 0, 3, 5)
akrun
  • 874,273
  • 37
  • 540
  • 662