【问题标题】:How to extract values from column based on string value in other column?如何根据其他列中的字符串值从列中提取值?
【发布时间】:2021-09-18 01:37:42
【问题描述】:

我有一个数据框 df:

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

我想从 x1 列中提取唯一值,如果同一行的 x3 列中的值在其中包含任何形式的单词 france(France,france,FrancE,...)。所以,想要的结果是:

x1
11
12
14

怎么做?

【问题讨论】:

    标签: r dataframe filter extract


    【解决方案1】:

    我们也可以使用

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

    【讨论】:

      【解决方案2】:

      您可以将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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-10-21
        • 2020-05-29
        • 1970-01-01
        • 2021-10-15
        • 1970-01-01
        • 1970-01-01
        • 2014-04-23
        相关资源
        最近更新 更多