I want to remove individuals from my df that have ANY values below a certain latitude. Specifically if individual "A" is in the dataset three times, and one of those times they are below the set latitude, I want all entries including that individual to be removed. Here is an example of what I want to achieve:
name <- c('a', 'b', 'c', 'a', 'a', 'b')
latitude <- c('50', '55', '55', '40', '57', '60')
df <- data.frame(name, latitude)
I want to remove all names with latitudes below 45. "A" has one entry below 45, so remove "A" from the data so it looks like this:
name latitude
1 b 55
2 c 55
3 b 60
Thus far what I've been doing is this:
df <- df %>% filter(latitude > 45)
name latitude
1 a 50
2 b 55
3 c 55
4 a 57
5 b 60
I know that's nowhere near the solution I need, but I had to start somewhere. I'm pretty new with R, so any detailed explanations would also be appreciated.
A base R code-golfing with subset
+ ave
> subset(df, !ave(latitude < 45, name))
name latitude
2 b 55
3 c 55
6 b 60
Base R solution
> with(df, df[!name %in% name[latitude<45], ])
name latitude
2 b 55
3 c 55
6 b 60
dplyr:
df %>%
filter( !name %in% name[latitude<45])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With