I would like to conditionally filter based on multiple conditions. I've seen many posts on this website that use if/else conditions for a filter, but never one with multiple conditions inside a single if statement.
Take the following sample data as an example:
data <- structure(list(names = c("Mike", "Mike", "Sam", "Sam", "Sam",
"Emma", "Jessica", "Jessica"), tries = c(1, 2, 3, 2, 2, 3, 1,
3)), class = "data.frame", row.names = c(NA, -8L))
data
names tries
1 Mike 1
2 Mike 2
3 Sam 3
4 Sam 2
5 Sam 2
6 Emma 3
7 Jessica 1
8 Jessica 3
In this specific example, I want to take the first and maybe the second row of each grouped name. I only want to keep the first row for a name if the number of tries is greater than 1. But, if the number of tries is equal to 1 then I want to keep the first two rows.
I have a workaround that technically does the job, but it doesn't seem like it should work. Here is my workaround:
library(tidyverse)
data %>%
group_by(names) %>%
filter(
if (row_number() == 1 & tries > 1) {
row_number() == 1
} else {
row_number() == 1 | row_number() == 2
}
)
# A tibble: 6 x 2
# Groups: names [4]
names tries
<chr> <dbl>
1 Mike 1
2 Mike 2
3 Sam 3
4 Emma 3
5 Jessica 1
6 Jessica 3
Warning messages:
1: In if (row_number() == 1 & tries > 1) { :
the condition has length > 1 and only the first element will be used
2: In if (row_number() == 1 & tries > 1) { :
the condition has length > 1 and only the first element will be used
3: In if (row_number() == 1 & tries > 1) { :
the condition has length > 1 and only the first element will be used
You can see that it does return the correct dataset, but it gives me tons of warnings and says that since there are multiple conditions inside the if statement then it will only use the first element. But, it seems like it is using both elements. Am I missing something here? Is there a tidyverse solution to this problem that avoids the warning messages?
Thanks for your help!
Aucun commentaire:
Enregistrer un commentaire