首页 > 解决方案 > 查找一个字符向量的哪个元素另一个向量的元素开始

问题描述

我有两个字符向量:

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

解决方案


使用sapply-

as.numeric(sapply(v1,function(x) which(sapply(v2,function(y) startsWith(x, y)))))

#[1] 2 2 2 3 3 1

推荐阅读