Question

I have data like the following:

ID Year Measurement
1  2009 5.6
1  2010 6.2
1  2011 4.5
2  2008 6.4
2  2009 5.2
3  2008 3.5
3  2010 5.6 
4  2009 5.9
4  2010 2.2
4  2011 4.1
4  2012 5.5

Where subjects are measured over a few years with different starting and ending years. Subjects are also measured a different number of times. I want to remove subjects that are not measured every single year between their start and end measurement years. So, in the above data I would want subject 3 removed since they missed a measurement in 2009.

I thought about doing a for loop where I get the maximum and minimum value of the variable Year for each unique ID. I then take the difference between the maximum and minimum for each player and add 1. I then count the number of times each unique ID appears in the data and check to see if they are equal. This ought to work but I feel like there has a got to be a quick and more efficient way to do this.

Était-ce utile?

La solution

This will be easiest with the data.table package:

dt = data.table(df, key="Year")
dt[,Remove:=any(diff(Year) > 1),by=ID]
dt = dt[(!Remove)]
dt$Remove = NULL

   ID Year Measurement
1:  1 2009         5.6
2:  1 2010         6.2
3:  1 2011         4.5
4:  2 2008         6.4
5:  2 2009         5.2
6:  4 2009         5.9
7:  4 2010         2.2
8:  4 2011         4.1
9:  4 2012         5.5

Autres conseils

Here's an alternative

> ind <- aggregate(Year~ID, FUN=function(x) x[2]-x[1], data=df)$Year>1
> df[!df$ID==unique(df$ID)[ind], ]
   ID Year Measurement
1   1 2009         5.6
2   1 2010         6.2
3   1 2011         4.5
4   2 2008         6.4
5   2 2009         5.2
8   4 2009         5.9
9   4 2010         2.2
10  4 2011         4.1
11  4 2012         5.5

You may try ave. My anonymous function is basically the pseudo code suggested in the question.

df[as.logical(ave(df$Year, df$ID, FUN = function(x) length(x) > max(x) - min(x))), ]

#    ID Year Measurement
# 1   1 2009         5.6
# 2   1 2010         6.2
# 3   1 2011         4.5
# 4   2 2008         6.4
# 5   2 2009         5.2
# 8   4 2009         5.9
# 9   4 2010         2.2
# 10  4 2011         4.1
# 11  4 2012         5.5
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top