I am writing code. But instead of counting the sum of all the values ​​that came up, it simply gives the last suitable value. How to save all suitable values?

filtered.sum <- function(x){ x[is.na(x)] <- 0 d <- 0 for (i in 1:length(x)) { if (x[i]>0){ s <- x[i] } } d <- d+s return(d) } 

    3 answers 3

    Obviously, d <- d+s needs to be transferred under if. And so a new value is written to s each time - and after exiting the loop, there, of course, is the last value.

    • I see this language for the first time, but strangely, why not d <- d+x[i] ? - splash58 pm
    • @Zufir thanks! I was close ... - Vitya Alexandrovich

    This code can be replaced by two lines:

     x[is.na(x)] <- 0 sum(x[x >= 0]) 
    • Yes, you are right, just wanted to understand how to do it with for + if - Vitya Alexandrovich
    • four
      It is still more correct to do this in one line (since in this case there is no change in the input data): sum(x[x >= 0], na.rm = TRUE) , but if you make an exact match to the solution from the condition, then yes. - Timofei Bondarev

    Another variant of cumsum (na.omit (x))