【问题标题】:R Column Check if Contains Value from Another ColumnR列检查是否包含来自另一列的值
【发布时间】:2020-08-13 18:11:24
【问题描述】:

R 中有没有办法检查一列中的值是否包含另一列中的值?在下面的示例中,我试图查看 col2 中的值是否包含在 col1 中的值中(独立地在每一行中),但收到一条警告消息:“argument 'pattern' has length > 1 and only the first element will be used ”。标志列应在第一行/最后一行显示“是”,在第二行和第三行显示“否”。任何关于如何解决的想法将不胜感激。

col1 <- c("R.S.U.L.C","S.I.W","P.U.E","A.E.N")
col2 <- c("R","U","I","N")

df2 <- data.frame(col1,col2)

df2$Flag <- ifelse(grepl(df2$col2,df2$col1),"Yes","No")

【问题讨论】:

    标签: r dataframe contains grepl


    【解决方案1】:

    我们可以使用str_detect,它对模式和字符串都进行了矢量化

    library(dplyr)
    library(stringr)
    df2 <- df2 %>% 
         mutate(Flag = c('No', 'Yes')[1+str_detect(col1, as.character(col2))])
    df2
    #       col1 col2 Flag
    #1 R.S.U.L.C    R  Yes
    #2     S.I.W    U   No
    #3     P.U.E    I   No
    #4     A.E.N    N  Yes
    

    【讨论】:

      【解决方案2】:

      df2$flag &lt;- mapply(grepl, df2$col2, df2$col1)

      grepl() 的模式参数只使用第一个元素:

      ?grepl:

      如果提供长度为 2 或更大的字符向量,则第一个 元素与警告一起使用。

      【讨论】:

        【解决方案3】:

        这可以通过sapply/grepl 的组合来完成。沿着 df2$colgrepl 在字符串 df$col1 中循环。
        单线很明显。

        i <- sapply(seq_along(df2$col2), function(i) grepl(df2$col2[i], df2$col1[i]))
        df2$Flag <- c("No", "Yes")[i + 1L]
        df2
        #       col1 col2 Flag
        #1 R.S.U.L.C    R  Yes
        #2     S.I.W    U   No
        #3     P.U.E    I   No
        #4     A.E.N    N  Yes
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-01-13
          • 1970-01-01
          • 2012-11-09
          • 2012-07-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多