Q: Assign value to new variable according to sequence in other variables I ran in to a problem when trying to create a specific type of variable using R.
First of all, my dataset looks something like this.
Company Year Employeeid
A       2011     2
A       2012     2 
A       2013     1      
A       2014     3
A       2015     4
B       2011     8
B       2012     1 
B       2013     19      
B       2014     19
B       2015     19
         etc...

So lets say that in this case what I'd want is to create a variable, let's call it variable A, that records a 1 for every observation where the company employs employee (id) for at least two years in a row. Otherwise the variable A should record a 0.
How would I go about doing this ? I was thinking about using double loops, but that got complicated very quickly.
Thanks in advance !!

A: We could use rle after grouping by 'Company' to create a logical expression
If it is to consider for each case separately, remove the any and use
library(dplyr)
df1 %>% 
     group_by(Company) %>%
     mutate(A = +(rep(with(rle(Employeeid), rep(lengths  >= 2, lengths))))) %>%
     ungroup
# A tibble: 10 x 4
   Company  Year Employeeid     A
   <chr>   <int>      <int> <int>
 1 A        2011          2     1
 2 A        2012          2     1
 3 A        2013          1     0
 4 A        2014          3     0
 5 A        2015          4     0
 6 B        2011          8     0
 7 B        2012          1     0
 8 B        2013         19     1
 9 B        2014         19     1
10 B        2015         19     1

data
df1 <- structure(list(Company = c("A", "A", "A", "A", "A", "B", "B", 
"B", "B", "B"), Year = c(2011L, 2012L, 2013L, 2014L, 2015L, 2011L, 
2012L, 2013L, 2014L, 2015L), Employeeid = c(2L, 2L, 1L, 3L, 4L, 
8L, 1L, 19L, 19L, 19L)), class = "data.frame", row.names = c(NA, 
-10L))


A: You could do:
df %>%
  arrange(Company, Employeeid, Year) %>%
  group_by(Company, Employeeid) %>%
  mutate(A = +any(c(0, diff(Year)) == 1))

# A tibble: 10 x 4
# Groups:   Company, Employeeid [7]
   Company  Year Employeeid     A
   <chr>   <int>      <int> <int>
 1 A        2011          2     1
 2 A        2012          2     1
 3 A        2013          1     0
 4 A        2014          3     0
 5 A        2015          4     0
 6 B        2011          8     0
 7 B        2012          1     0
 8 B        2013         19     1
 9 B        2014         19     1
10 B        2015         19     1

