我有一个dataframe (peak.anno_C1_4),它有5578个obs和19个变量,以及一个值列表(intestine_unique),我想检查它们是否在dataframe的一个列中,如果它们在其中,我希望在一个新的dataframe中提取相应的行(包含所有19个变量)。
intestine_unique <- c("atm-1", "cdc-3", "fgf-5")
peak.anno_C1_4
chr start end name
1 12345 12347 atm-1
1 2345 2344 cdc-3
2 3456 3455 fgf-5
2 4567 4566 dfr-3我只想要前三行,所以我做了这个循环,但它不工作
intestine<-data.frame()
for (i in 1:length(intestine_unique)){
for (j in 1:length(peak.anno_C1_4$SYMBOL)){
if (i == j)
intestine <- peak.anno_C1_4
}
}有人能帮我吗?
发布于 2022-11-01 12:46:19
我能想象到这有几种方式。如果要查找任何完整的字符串匹配,可以使用if_any和%in%。或者,您可能需要查找部分字符串匹配,在这种情况下,我将使用grepl。注意完整的部分字符串匹配的输出差异。我以这里的starwars数据集为例。
library(tidyverse)
vals <- c("red", "Watto")
data <- starwars |>
select(name, hair_color, skin_color, eye_color)
#full string mataches
data |>
filter(if_any(everything(), \(x) x %in% vals))
#> # A tibble: 7 x 4
#> name hair_color skin_color eye_color
#> <chr> <chr> <chr> <chr>
#> 1 R2-D2 <NA> white, blue red
#> 2 R5-D4 <NA> white, red red
#> 3 IG-88 none metal red
#> 4 Bossk none green red
#> 5 Nute Gunray none mottled green red
#> 6 Watto black blue, grey yellow
#> 7 Darth Maul none red yellow
#partial string matches
data |>
filter(if_any(everything(), \(x) grepl(paste(vals, collapse = "|"), x)))
#> # A tibble: 10 x 4
#> name hair_color skin_color eye_color
#> <chr> <chr> <chr> <chr>
#> 1 R2-D2 <NA> white, blue red
#> 2 R5-D4 <NA> white, red red
#> 3 IG-88 none metal red
#> 4 Bossk none green red
#> 5 Nute Gunray none mottled green red
#> 6 Watto black blue, grey yellow
#> 7 Sebulba none grey, red orange
#> 8 Darth Maul none red yellow
#> 9 R4-P17 none silver, red red, blue
#> 10 Shaak Ti none red, blue, white blackhttps://stackoverflow.com/questions/74276061
复制相似问题