如何根据其他列中的字符串值从列中提取值?

How to extract values from column based on string value in other column?

我有一个数据框 df:

x1   x2          x3
11   john     France-back
12   brad     france-present
13   alex     italy-back
14   chris    FrancE-forward

我想从 x1 列中提取唯一值,前提是同一行的 x3 列中的值以任何形式(France、france、FranE 等)包含单词 france。所以,期望的结果是:

x1
11
12
14

怎么做?

您可以将 greplignore.case = TRUE 一起使用。

res <- data.frame(x1 = unique(df$x1[grepl('france', df$x3, ignore.case = TRUE)]))
res

#  x1
#1 11
#2 12
#3 14

使用tidyverse

library(dplyr)
library(stringr)

df %>%
  filter(str_detect(x3, fixed('france', ignore_case = TRUE))) %>%
  distinct(x1)

我们也可以用

library(dplyr)
df %>%
  filter(grepl("france" x3, ignore.case = TRUE)) %>%
  distinct(x1)