Long data - delete all rows when first value for each person = XR

I have a long dataframe like the one below. I want to limit the data frame to people who were over 65 at the first observation. Please note during the research that 65 is canceled during the research, I do not want to delete any of its data. This is because its first value is <65.

I tried to make a function .... I thought that if I could make an indicator variable when the first person's first value is> 65, then I could exclude the rows of persons.

df$first<-ave(df$string, df$id, FUN=function(x) [1]>65)  ##wrong!



 id string
1    pat     71
2    pat     72
3    pat     73
4    pat     74
5    tom     51
6    tom     52
7    tom     53
8    tom     54
9    sue     63
10   sue     64
11   sue     65
12   sue     66
13  mary     68
14  mary     69
15  mary     70
16  mary     71
17 harry     17
18 harry     18
19 harry     19
20 harry     20

      

Can anyone shed some light on this please?

+3


source to share


1 answer


you can use

df[as.logical(with(df, ave(string, id, FUN= function(x) x[1] < 65))),]

      



Or using data.table

library(data.table)
setDT(df)[, .SD[string[1L] <65] , id]

      

+3


source







All Articles