R中一个向量元素在另一个向量中的位置

5
我希望创建一个包含一个向量中元素位置的另一个向量。类似于以下问题:如何获取一个向量中元素在另一个向量中的索引? 是否有R函数可以找到向量中元素的索引? 在最简单的情况下,基本的 R 中的 match 函数可以起到作用:
a <- c(1,1,2,2,3,3,4,4,5,5)
b <- c(1,2,3,4,5)
desired.output <- c(1,3,5,7,9)
match(b,a)
#[1] 1 3 5 7 9

然而,match 在下面更为复杂的情况中似乎无法正常工作。我可能需要结合使用whichmatch。到目前为止,在我考虑的每种情况中,b中的值在a中的出现次数不会比b中的出现次数更多。我需要一个基本的 R 解决方案。

a <- c(1,1,2,2,3,3,4,4,5,5)
b <- c(1,2,2,3,4,5)
desired.output <- c(1,3,4,5,7,9)

a <- c(1,1,2,2,3,3,4,4,5,5)
b <- c(1,2,2,3,4,4,5)
desired.output <- c(1,3,4,5,7,8,9)

a <- c(1,1,2,2,3,3,4,4,5,5)
b <- c(1,2,2,3,4,4,5,5)
desired.output <- c(1,3,4,5,7,8,9,10)

a <- c(1,1,2,2,3,3,4,4,5,5)
b <- c(1,1,2,2,3,4,4,5,5)
desired.output <- c(1,2,3,4,5,7,8,9,10)

a <- c(1,1,2,2,3,3,4,4,5,5)
b <- c(1,1,2,2,3,3,4,4,5,5)
desired.output <- c(1,2,3,4,5,6,7,8,9,10)

  1. 写一个函数,用于在向量中找到某个数字的第n次出现的索引。
  2. 对于b中的每个值,在对a应用该函数的同时计算出现次数。
  3. 将结果放入向量中,通过 result <- c(result, newValue) 实现。
  4. 利润。
- Shamis
1个回答

5
对于给定的情况,pmatch将给出所需的结果。结合make.unique使用match也可以工作。如果速度很重要,可以使用split或使用Rcpp 的函数。还可以查看Efficiently match all values of a vector in another vector
pm <- function(x, y) {
    a <- split(seq_along(x), x)
    b <- split(seq_along(y), y)[names(a)]
    b[lengths(b)==0] <- NA
    b <- unlist(Map(`length<-`, b, lengths(a)), FALSE, FALSE)
    `[<-`(b, unlist(a, FALSE, FALSE), b) }

Rcpp::sourceCpp(code=r"(
#include <Rcpp.h>
#include <unordered_map>
#include <queue>

using namespace Rcpp;
// [[Rcpp::export]]
IntegerVector pmC(NumericVector a, NumericVector b) {
  IntegerVector idx(no_init(a.size()));
  std::unordered_map<float, std::queue<int> > lut;
  for(int i = 0; i < b.size(); ++i) lut[b[i]].push(i);
  for(int i = 0; i < idx.size(); ++i) {
    auto search = lut.find(a[i]);
    if(search != lut.end() && search->second.size() > 0) {
      idx[i] = search->second.front() + 1;
      search->second.pop();
    } else {idx[i] = NA_INTEGER;}
  }
  return idx;
}
)")

a <- c(1,1,2,2,3,3,4,4,5,5)
b <- c(1,2,3,4,5)
pmatch(b,a)
match(make.unique(as.character(b)), make.unique(as.character(a)))
pm(b,a)
pmC(b,a)
#[1] 1 3 5 7 9

a <- c(1,1,2,2,3,3,4,4,5,5)
b <- c(1,2,2,3,4,5)
pmatch(b,a)
match(make.unique(as.character(b)), make.unique(as.character(a)))
pm(b,a)
pmC(b,a)
#[1] 1 3 4 5 7 9

a <- c(1,1,2,2,3,3,4,4,5,5)
b <- c(1,2,2,3,4,4,5)
pmatch(b,a)
match(make.unique(as.character(b)), make.unique(as.character(a)))
pm(b,a)
pmC(b,a)
#[1] 1 3 4 5 7 8 9

a <- c(1,1,2,2,3,3,4,4,5,5)
b <- c(1,2,2,3,4,4,5,5)
pmatch(b,a)
match(make.unique(as.character(b)), make.unique(as.character(a)))
pm(b,a)
pmC(b,a)
#[1]  1  3  4  5  7  8  9 10

a <- c(1,1,2,2,3,3,4,4,5,5)
b <- c(1,1,2,2,3,4,4,5,5)
pmatch(b,a)
match(make.unique(as.character(b)), make.unique(as.character(a)))
pm(b,a)
pmC(b,a)
#[1]  1  2  3  4  5  7  8  9 10

a <- c(1,1,2,2,3,3,4,4,5,5)
b <- c(1,1,2,2,3,3,4,4,5,5)
pmatch(b,a)
match(make.unique(as.character(b)), make.unique(as.character(a)))
pm(b,a)
pmC(b,a)
# [1]  1  2  3  4  5  6  7  8  9 10

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接