基于部分匹配的列的子集df

时间:2018-09-24 21:08:31

标签: r grep match

我想基于2列之间的部分匹配来对我的df进行子集化。我的df的示例: A B value 1 ABCDEFG CDEF 25 2 HIJKLMN CDEF 36 3 OPQRST CDEF 21 4 ABCDEFG KLMN 25 5 HIJKLMN KLMN 69 6 OPQRST KLMN 98 7 ABCDEFG PQR 85 8 HIJKLMN PQR 74 9 OPQRST PQR 58

structure(list(A = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L,3L), .Label = c("ABCDEFG", "HIJKLMN", "OPQRST"), class = "factor"), B = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), .Label = c("CDEF", "KLMN", "PQR"), class = "factor"), value = c(25L, 36L, 21L,25L, 69L, 98L, 85L, 74L, 58L)), .Names = c("A", "B", "value"), class = "data.frame", row.names = c(NA, -9L))

我想对B列与A列部分匹配的行进行子集化。对于此示例,预期输出为:

A B value 1 ABCDEFG CDEF 25 2 OPQRST PQR 58 3 HIJKLMN KLMN 69

1 个答案:

答案 0 :(得分:0)

一个选项是

library(tidyverse)
df1 %>% 
   filter(str_detect(A, as.character(B)))
#        A    B value
#1 ABCDEFG CDEF    25
#2 HIJKLMN KLMN    69
#3  OPQRST  PQR    58