how to deal with lag in a for loop

Good evning i want to run a lag() function inside the loop and make the counter of loop inside the function i wanna say : if lag( review) from the dataset with the index i is equal 1 then give rewiew_tabloid the value 1.

for(i in 1:10) {
  if (lag(Dataset$review, n="i")==1) {review_tabloid <-1}

could you please help me and tell me what was wrong . sorry this fucnction Lag is new for me. thank you in advance

Dont loop - Use functional programming. Inspirational example:

d <- tibble(x = rnorm(20))
d %>% 
  mutate(y = case_when(x > 0 ~ 1,
                       x == 0 ~ 0,
                       x < 0 ~ -1))

Hope it helps :slightly_smiling_face:

Thank you Leon . i like the Idea of functional Progarmming . i will try it today.
Thank you

If you really want to harness the full power of the small example I showed you - I recommend you going through R for Data Science back-to-back. It's well worth the energy input :+1:

So there are few issues with your code:

  1. I'm not sure which lag() function you want. Is it dplyr::lag or stats::lag. To avoid bugs, be explicit
  2. With n="i" the value of i never changes. Instead, you would have n = i
  3. Also lag(Dataset$review, n=1)==1 will return more than one value. The operator == only works when comparing two scalers

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.