代码之家  ›  专栏  ›  技术社区  ›  Hope

逐个计算向量中多个数字的出现次数

  •  1
  • Hope  · 技术社区  · 6 年前

    我有两个向量

    a <- c(1, 5, 2, 1, 2, 3, 3, 4, 5, 1, 2)
    b <- (1, 2, 3, 4, 5, 6)
    

    我想知道B中的每个元素出现了多少次,所以结果应该是

    c(3, 3, 2, 1, 2, 0)
    

    我发现的所有方法 match() , == , %in% 等不适用于整个矢量。我知道我可以在b中的所有元素上使用循环,

    for (i in 1:length(b)) {
        c[I] <- sum(a==b, na.rm=TRUE)
    }
    

    但这是经常使用,需要很长时间。这就是为什么我在寻找一种矢量化的方法,或者一种使用的方法。 apply() .

    3 回复  |  直到 6 年前
        1
  •  2
  •   Maurits Evers    6 年前

    你可以用 factor table

    table(factor(a, unique(b)))
    #
    #1 2 3 4 5 6
    #3 3 2 1 2 0
    

    自从你提到 match ,有可能没有 sapply 循环(感谢@thelatemail)

    table(factor(match(a, b), unique(b)))
    #
    #1 2 3 4 5 6
    #3 3 2 1 2 0
    
        2
  •  2
  •   Tim Biegeleisen    6 年前

    下面是一个基r选项,使用 sapply 具有 which :

    a <- c(1, 5, 2, 1, 2, 3, 3, 4, 5, 1, 2)
    b <- c(1, 2, 3, 4, 5, 6)
    
    sapply(b, function(x) length(which(a == x)))
    [1] 3 3 2 1 2 0
    

    Demo

        3
  •  1
  •   dww Jarretinha    6 年前

    下面是一个矢量化方法

    x = expand.grid(b,a)
    rowSums( matrix(x$Var1 == x$Var2, nrow = length(b)))
    # [1] 3 3 2 1 2 0