[Solved] How to generate a “range” variable in R? [duplicate]


Here’s a base R one-liner use ave:

df$A <- ave(df$X, df$Subject, FUN = function(x) if (max(x) == 3) 1 else 0)

> df
   Subject Year X A
1        A 1990 1 0
2        A 1991 1 0
3        A 1992 2 0
4        A 1993 3 0
5        A 1994 4 0
6        A 1995 4 0
7        B 1990 0 0
8        B 1991 1 0
9        B 1992 1 0
10       B 1993 2 0
11       C 1991 1 1
12       C 1992 2 1
13       C 1993 3 1
14       C 1994 3 1
15       D 1991 1 0
16       D 1992 2 0
17       D 1993 3 0
18       D 1994 4 0
19       D 1995 5 0
20       D 1996 5 0
21       D 1997 6 0

4

solved How to generate a “range” variable in R? [duplicate]