0

How can I achieve same results without loop? It's equivalent of scan function in reactiveX but with custom logic (http://reactivex.io/rxjs/img/scan.png)

for (i in 2:nrow(x)) {
  x$running_number[i] <-
    ifelse(abs(x$running_number[(i - 1)] - x$numbers[i])  > max_diff,
           x$numbers[i],
           x$running_number[(i - 1)])
}

EDIT:

Not sure I asked correctly after your reply. Take a look at this dataframe

x <- data.frame(
  c(1000, 1010, 1020, 1030, 1100, 1120, 1140, 1150, 1200),
  c(1000, 1000, 1000, 1000, 1100, 1100, 1100, 1100, 1200)
)

colnames(x) <- c('input_v', 'output_v')

Given x$input_v need to get x$output_v

I can express condition like :

x$output_v <-
  ifelse(
    abs(x$input_v - somehow_get_me_last_assigned_x_output_v) > 90,
    x$input_v,
    somehow_get_me_last_assigned_x_output_v
  )

1 Answer 1

1

We can use diff to find the difference between the adjacent elements, create the logical condition with 'max-diff', use that in ifelse to return either the 'numbers' or the lag of 'running_number'

with(x, ifelse(c(FALSE, abs(diff(running_number)) > max_diff), 
      numbers, c(NA, running_number[-nrow(x)])))

Or with dplyr

library(dplyr)
x %>%
  mutate(running_number = case_when(c(FALSE, abs(diff(running_number)) > 
             max_diff)0 ~ numbers, TRUE ~ lag(running-number))) 
Sign up to request clarification or add additional context in comments.

1 Comment

@AndrewVorobyov. i think the logic with max_diff which is 70 may not work in the example you updated. YOu can try with(x, ave(input_v, cumsum(c(TRUE, diff(input_v) > 20)), FUN = function(x) x[1])) [1] 1000 1000 1000 1000 1100 1100 1100 1100 1200

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.