R 相当于 SQL SELECT COUNT(*) ... GROUP BY

R equivalent of SQL SELECT COUNT(*) ... GROUP BY

我正在寻找如何计算向量中每种类型的整数的数量。例如,有多少个 1、2 和 3(没有硬编码 == 1,2,3):

test_vec = c(1,2,3,1,2,1,2,1,1,1,2,1,3,1,2,3,2,1,2,1,3)

以及,如何识别我向向量中添加了一些 4 并计算它们?

test_vec = c(test_vec,4,4,4)

我可以用 range() 和一个循环来做到这一点,但想知道是否有通用的向量化解决方案?

编辑:与 this 不同的问题,因为该问题不询问一般化的 table 情况(尽管答案明智地表明了这一点),而是检查硬编码的相等性 sum(test_vec==x)

你可以使用table

table(test_vec)
test_vec
 1  2  3 
10  7  4 

到你问题的第二部分

> which(test_vec == 4)

[1] 22 23 24  # gives you their position in the vector in order to "identify" them

> sum(test_vec == 4) 

[1] 3 # counts the 4's in the vector

编辑:正如我们在这里提到的一切,

tapply(test_vec, test_vec, length)

也可以

 1  2  3 
10  7  4

您也可以使用 data.table 包来计算每个组中的元素数量。

library(data.table)
as.data.table(x = test_vec)[, .N, by=x]
#   x  N
#1: 1 10
#2: 2  7
#3: 3  4
#4: 4  3

.N是一个特殊的内置变量,是一个长度为1的整数。它包含每组中的观察次数。

dplyr 方法:

test_vec = c(1,2,3,1,2,1,2,1,1,1,2,1,3,1,2,3,2,1,2,1,3)
library(dplyr)
df <- data_frame(test_vec)

df %>% 
    count(test_vec)

# Alternative that shows group_by
df %>%
    group_by(test_vec) %>%
    summarise(n = n()) # or tally()

#   test_vec  n
# 1        1 10
# 2        2  7
# 3        3  4

aggregate 在这种情况下非常方便

> aggregate(data.frame(count = test_vec), list(value = test_vec), length)

  value count
1     1    10
2     2     7
3     3     4