Counting the number of elements with the values of x in a vector

后端 未结 19 1297
闹比i
闹比i 2020-11-22 02:44

I have a vector of numbers:

numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435,
         453,435,324,34,456,56,567,65,34,435)

How can I hav

相关标签:
19条回答
  • 2020-11-22 03:34

    Here is a way you could do it with dplyr:

    library(tidyverse)
    
    numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435,
                 453,435,324,34,456,56,567,65,34,435)
    ord <- seq(1:(length(numbers)))
    
    df <- data.frame(ord,numbers)
    
    df <- df %>%
      count(numbers)
    
    numbers     n
         <dbl> <int>
     1       4     2
     2       5     1
     3      23     2
     4      34     2
     5      43     1
     6      54     1
     7      56     2
     8      65     1
     9      67     2
    10     324     1
    11     435     3
    12     453     1
    13     456     1
    14     567     1
    15     657     1
    
    0 讨论(0)
  • 2020-11-22 03:35

    The most direct way is sum(numbers == x).

    numbers == x creates a logical vector which is TRUE at every location that x occurs, and when suming, the logical vector is coerced to numeric which converts TRUE to 1 and FALSE to 0.

    However, note that for floating point numbers it's better to use something like: sum(abs(numbers - x) < 1e-6).

    0 讨论(0)
  • 2020-11-22 03:38

    There is a standard function in R for that

    tabulate(numbers)

    0 讨论(0)
  • 2020-11-22 03:38

    If you want to count the number of appearances subsequently, you can make use of the sapply function:

    index<-sapply(1:length(numbers),function(x)sum(numbers[1:x]==numbers[x]))
    cbind(numbers, index)
    

    Output:

            numbers index
     [1,]       4     1
     [2,]      23     1
     [3,]       4     2
     [4,]      23     2
     [5,]       5     1
     [6,]      43     1
     [7,]      54     1
     [8,]      56     1
     [9,]     657     1
    [10,]      67     1
    [11,]      67     2
    [12,]     435     1
    [13,]     453     1
    [14,]     435     2
    [15,]     324     1
    [16,]      34     1
    [17,]     456     1
    [18,]      56     2
    [19,]     567     1
    [20,]      65     1
    [21,]      34     2
    [22,]     435     3
    
    0 讨论(0)
  • 2020-11-22 03:41

    This can be done with outer to get a metrix of equalities followed by rowSums, with an obvious meaning.
    In order to have the counts and numbers in the same dataset, a data.frame is first created. This step is not needed if you want separate input and output.

    df <- data.frame(No = numbers)
    df$count <- rowSums(outer(df$No, df$No, FUN = `==`))
    
    0 讨论(0)
  • 2020-11-22 03:43

    I would probably do something like this

    length(which(numbers==x))
    

    But really, a better way is

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