假設我有以下資料集 test
> test = data.frame(location = c("here", "there", "here", "there", "where"), x = 1:5, y = c(6,7,8,6,10))
> test
location x y
1 here 1 6
2 there 2 7
3 here 3 8
4 there 4 6
5 where 5 10
然后,我想創建一個條件,如果y滿足條件,則在資料集中維護匹配一次的每個位置,例如
test %>% filter_something(y == 6)
location x y
1 here 1 6
2 there 2 7
3 here 3 8
4 there 4 6
請注意,即使在第 4 行中也沒有y = 6,它們會保留在資料集上,因為至少有一種情況location與 'right' 匹配y。
我可以解決這個問題,使用 創建另一個資料集y == 6,然后使用 進行內部連接test,但是如果有另一個更優雅的選項,有什么提示嗎?,因為我不只是過濾這個變數,但我也在使用其他列。
uj5u.com熱心網友回復:
我們可以group_by定位,然后使用any(condition)
library(dplyr)
test %>% group_by(location) %>%
filter(any(y==6))
uj5u.com熱心網友回復:
如果我們想使用 data.table,我們可以先獲取與 y ==6 關聯的位置,然后過濾這些位置,所有這些都在一行中:
library(data.table)
test <- setDT(test)
# keep only the locations associated with y == 6
test <- test[location %in% test[y==6]$location]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/354173.html
上一篇:R:回傳所有簡單路徑的邊串列
