我有一个数字向量:

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

我如何让R计算x值在向量中出现的次数?


当前回答

一个选项是使用vctrs库中的vec_count()函数:

vec_count(numbers)

   key count
1  435     3
2   67     2
3    4     2
4   34     2
5   56     2
6   23     2
7  456     1
8   43     1
9  453     1
10   5     1
11 657     1
12 324     1
13  54     1
14 567     1
15  65     1

默认顺序将最常用的值放在顶部。如果根据键进行排序(类似table()的输出):

vec_count(numbers, sort = "key")

   key count
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

其他回答

最直接的方法是求和(numbers == x)。

numbers == x创建一个在x出现的每个位置都为TRUE的逻辑向量,当求和时,逻辑向量被强制转换为numeric,将TRUE转换为1,FALSE转换为0。

但是,请注意,对于浮点数,最好使用如下格式:sum(abs(numbers - x) < 1e-6)。

如果你想计算随后出现的次数,你可以使用sapply函数:

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

输出:

        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

您可以在下面一行中将数字更改为您希望的任何数字

length(which(numbers == 4))

我可能会这样做

length(which(numbers==x))

但实际上,更好的方法是

table(numbers)

使用表,但不与名称比较:

numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435)
x <- 67
numbertable <- table(numbers)
numbertable[as.character(x)]
#67 
# 2 

当您多次使用不同元素的计数时,Table非常有用。如果你只需要一个计数,使用sum(numbers == x)