【问题标题】:Find which element of one character vector another vector's elements start with查找一个字符向量的哪个元素另一个向量的元素开始
【发布时间】:2021-07-17 01:55:06
【问题描述】:

我有两个字符向量:

v1 <- c("Red 1", "Red 2", "Red 3", "Blue thing", "Blue car", "Yellow anything")
v2 <- c("Yellow", "Red", "Blue")

我想得到一个向量,长度为 v1,包含它开始的元素在 v2 中的索引。

# Desired result
result <- c(2, 2, 2, 3, 3, 1)

我尝试查看which()startsWith() 的某种组合,但无法对这两个向量的操作进行向量化。

【问题讨论】:

    标签: r


    【解决方案1】:

    使用sapply -

    as.numeric(sapply(v1,function(x) which(sapply(v2,function(y) startsWith(x, y)))))
    
    #[1] 2 2 2 3 3 1
    

    【讨论】:

      【解决方案2】:

      我们可以使用outer 来提高效率

      which(t(outer(v1, v2, FUN = function(x, y) startsWith(x, y))), arr.ind = TRUE)[,1]
      [1] 2 2 2 3 3 1
      

      【讨论】:

        【解决方案3】:

        也许我们可以试试gsub + match 如下所示

        > match(gsub(sprintf("[^(%s)]", paste0(v2, collapse = "|")), "", v1), v2)
        [1] 2 2 2 3 3 1
        

        > match(gsub("\\s.*", "", v1), v2)
        [1] 2 2 2 3 3 1
        

        【讨论】:

          猜你喜欢
          • 2014-05-21
          • 2022-12-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多