R检查数据帧中是否存在元素并返回其索引

问题描述 投票:0回答:3

我的数据框看起来像这样

index     id
1         abc;def;ghi;jkl;mno
2         bcd;efg;hij;klm;nop
3         cde;fgh;ijk;lmn;opq
.
.
.

我想使用R来查找“abc”是否在数据帧中并返回其索引。

我试图将'id'列分隔为5个不同的列,并查找每行中是否有“abc”。但我的数据集包含大约200,000行。循环遍历每一行需要很长时间。我想知道是否有更有效的方法来检测它。

例如,“abc”是df $ id [1]的一部分,那么结果应该返回1; “cde”应该返回3。

r
3个回答
2
投票

您可以将which函数与grepl结合使用,如下所示:

which(grepl("abc", df$id))

如果“abc”包含在字符串中,grepl将返回TRUE,否则返回FALSEwhich返回包含TRUE的条目索引。

或者甚至更容易使用grep

grep("abc", df$id)

1
投票

尝试:

library(stringr)

df[str_detect(df$id, "abc"), "index"]

1
投票

我最近一直在使用%g%运算符(灵感来自%in%)来做这类事情:

library(tidyverse)

`%g%` <- function(x,y) {
  z <- paste0(y, collapse = "|")
  grepl(z, x, ignore.case = T)
}

df <- read.table(h = T,
                 stringsAsFactors = F,
                 text = "index     id
                         1         abc;def;ghi;jkl;mno
                         2         bcd;efg;hij;klm;nop
                         3         cde;fgh;ijk;lmn;opq")

df %>% 
  filter(id %g% "abc") %>% 
  pull(index)
#> [1] 1

df %>% 
  filter(id %g% "cde") %>% 
  pull(index)
#> [1] 3

这也支持多个值:

df %>% 
  filter(id %g% c("abc", "cde")) %>% 
  pull(index)
#> [1] 1 3

reprex package创建于2019-04-24(v0.2.1)

© www.soinside.com 2019 - 2024. All rights reserved.