Stack Overflow Asked by Cirrus on January 31, 2021
This seems very simple problem but could not figure out or find a solution in OS (this is not duplicate). In an example dff
below, I want to extract events that are common in both 5 and 6 (mn
value), i.e., In this example, how to extract dff
to get only Event2
in a new dataframe.
dff<-structure(list(ev = c("Event1", "Event1", "Event1", "Event1",
"Event1", "Event1", "Event1", "Event1", "Event1", "Event2", "Event2",
"Event2", "Event2", "Event2", "Event2", "Event2", "Event2", "Event2",
"Event2", "Event2", "Event3", "Event3", "Event3", "Event3"),
mn = c(5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6)), row.names = c(NA, -24L), class = c("tbl_df",
"tbl", "data.frame"))
dff
A base R option using aggregate
+ unique
> aggregate(. ~ ev, unique(dff), function(x) length(x) > 1)
ev mn
1 Event1 FALSE
2 Event2 TRUE
3 Event3 FALSE
Answered by ThomasIsCoding on January 31, 2021
Or an option with data.table
library(data.table)
unique(setDT(dff)[dff[, .I[uniqueN(mn) > 1], ev]$V1])
Answered by akrun on January 31, 2021
dff %>%
group_by(ev) %>%
filter(length(unique(mn)) > 1) %>%
unique()
OR maybe
dff %>%
group_by(ev) %>%
summarise(chk = all(c(5, 6) %in% mn))
Answered by d.b on January 31, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP