uhClem uhClem - 2 months ago 4
R Question

R: subsetting all observations of individuals that have one matched observation

Sorry for another dang subsetting question; I just can't find this case described, though it must be common. Boiled-down data looks like this:

Plot Year BA
A 1980 44
A 1990 54
A 2000 66
B 1980 58
B 1990 69
B 2000 80


I want all observations for any plot with BA < 50 in 1980 -- in the above, all three A rows. I understand
subset(Df, BA<50 & Year==1980)
but can't figure out the next level of indexing.

Also if anyone has a better way to phrase the title I'll change it. Every way I could think of to search on only turned up the &/| questions. (So many &/| questions...)

Answer

Index your condition on Plot, checking membership with %in% in case there is more than one Plot satisfying the condition in the real data.

subset(df, Plot %in% unique(Plot[BA < 50 & Year == 1980]))
#   Plot Year BA
# 1    A 1980 44
# 2    A 1990 54
# 3    A 2000 66

Or with standard evaluation [ subsetting,

df[with(df, Plot %in% unique(Plot[BA < 50 & Year == 1980])), ]
#   Plot Year BA
# 1    A 1980 44
# 2    A 1990 54
# 3    A 2000 66
Comments