[英]Subsetting strings from a column if they match multiple strings in a different column
我有一個 dataframe ,我想在其中對列進行子集化,以僅包含與不同列中的多個字符串匹配的字符串。 這是一些模擬數據:
df1 <- data.frame(species = c("Rufl","Rufl","Soca","Assp","Assp","Elre"),
state = c("warmed","ambient","warmed","warmed","ambient","ambient"))
我想要一個 dataframe,其中只有與“溫暖”和“環境”狀態匹配的物種,刪除僅匹配一個字符串的物種,因此最終的 dataframe 將具有“Rufl”和“Assp”及其給定狀態,如如下圖
species state
Rufl warmed
Rufl ambient
Assp warmed
Assp ambient
我已經嘗試了一些不同的嘗試,包括子集 function 和 dplyr,但無法找出正確的方法來讓它工作。 這是我失敗的嘗試:
df2 <- subset(df1$species, state == "warmed" & state == "ambient")
# or this?
df2 <- df1 %>%
group_by(species) %>%
filter(state == "warmed",
state == "ambient")
謝謝您的幫助!
使用 R 版本 4.0.2,Mac OS X 10.13.6
我們需要一個由all
組成的小組
library(dplyr)
df1 %>%
group_by(species) %>%
filter(all(c('warmed', 'ambient') %in% state)) %>%
ungroup
-輸出
# A tibble: 4 x 2
# species state
# <chr> <chr>
#1 Rufl warmed
#2 Rufl ambient
#3 Assp warmed
#4 Assp ambient
&
操作不起作用,因為元素不在同一位置
或使用subset
subset(df1, species %in% names(which(rowSums(table(df1) > 0) == 2)))
另一個使用ave
的基本 R 選項
subset(
df1,
ave(state, species, FUN = function(x) sum(c("warmed", "ambient") %in% x)) == 2
)
給
species state
1 Rufl warmed
2 Rufl ambient
4 Assp warmed
5 Assp ambient
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.