title: How to add grouping variable to data set that will classify both an observation and its N neighbors based on some condition
body: <p>I am having some trouble coming up with a solution that properly handles classifying a variable number of neighbors for any given observation in a data frame based on some condition. I would like to be able to add a simple, binary indicator variable to a data frame that will equal 1 if the condition is satisfied, and 0 if it is not.</p>
  
  <p>Where I am getting stuck is I am unsure how to iteratively check the condition against neighboring observations only, in either direction (i.e., to check if out of 4 neighboring observations in a given column in my data frame, that at least 3 out of 4 of them contain the same value). I have tried first creating another indicator variable indicating if the condition is satisfied or not (1 or 0 = yes or no). Then, I tried setting up a series of <code>ifelse()</code> statements within a loop to try to assign the proper categorization of the observation where the initial condition is satisfied, +/- 2 observations in either direction. However, when I inspect the dataframe after running the loop, only the observation itself (not its neighbors) where the condition is satisfied is receiving the value, rather than all neighboring observations also receiving the value. Here is my code:</p>
  
  <pre><code>#sample data
  sample_dat &lt;- data.frame(initial_ind = c(0,1,0,1,0,0,1,1,0,1,0,0))
  
  sample_dat$violate &lt;- NULL
  for(i in 1:nrow(dat_date_ord)){
    sample_dat$violate[i] &lt;- ifelse(sample_dat$initial_ind[i]==1 &amp;
                                           ((sample_dat$initial_ind[i-2]==1 |
                                               sample_dat$initial_ind[i-1]==1) &amp;
                                              (sample_dat$initial_ind[i+2]==1 |
                                                 sample_dat$initial_ind[i+1]==1)),
                                         "trending",
                                         "non-trending"
    )
  }
  
  
  </code></pre>
  
  <p>This loop correctly identifies one of the four points that needs to be labelled "trending", but it does not also assign "trending" to the correct neighbors. In other words, I expect the output to be "trending for observations 7-10, since 3/4 observations in that group of 4 all have a value of 1 in the initial indicator column. I feel like there might be an easier way to accomplish this - but what I need to ensure is that my code is robust enough to identify and assign observations to a group regardless of if I want 3/4 to indicate a group, 5/6, 2/5, etc.</p>
  
  <p>Thank you for any and all advice.</p>