r - 查找一个字符向量的哪个元素另一个向量的元素开始
问题描述
我有两个字符向量:
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()
无法对两个向量上的操作进行矢量化。
解决方案
使用sapply
-
as.numeric(sapply(v1,function(x) which(sapply(v2,function(y) startsWith(x, y)))))
#[1] 2 2 2 3 3 1
推荐阅读
- c++ - 在处理递归错误时非法使用显式模板参数
- javascript - 尝试使用 AnimeJS 进行变形时,为什么我的 SVG 路径会跳跃?
- c# - 使用 SHA256CryptoServiceProvider 时出现实体验证错误
- powershell - Powershell 如果成功或错误发送电子邮件
- google-maps - Flutter + Google Maps:如何将相机动画到目标位置
- multithreading - 重温:如何将不可变参数传递给线程?(关于一生)
- python - 如何保持和运行程序始终形成最后一个值,所以当我再次打开程序时,程序从最后一个数量开始
- flutter - 使用 onGenerateRoute 的屏幕之间的条件退出转换
- python-3.x - 在虚拟环境中安装 PyObjC 时出错
- ruby-on-rails - Rails 6图像显示在heroku本地但不在服务器上