Count occurence of multiple numbers in vector one by one

后端 未结 3 1332
旧时难觅i
旧时难觅i 2021-01-24 05:07

I have two vectors

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

I want to know how many times each element in b occur

相关标签:
3条回答
  • 2021-01-24 05:54

    Here is a vectorised method

    x = expand.grid(b,a)
    rowSums( matrix(x$Var1 == x$Var2, nrow = length(b)))
    # [1] 3 3 2 1 2 0
    
    0 讨论(0)
  • 2021-01-24 06:05

    You can do this using factor and table

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

    Since you mentioned match, here is a possibility without sapply loop (thanks to @thelatemail)

    table(factor(match(a, b), unique(b)))
    #
    #1 2 3 4 5 6
    #3 3 2 1 2 0
    
    0 讨论(0)
  • 2021-01-24 06:06

    Here is a base R option, using sapply with 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

    0 讨论(0)
提交回复
热议问题