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

后端 未结 19 1825
闹比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: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
    

提交回复
热议问题