如何在 R 的 data.table 对象列中查找每个类别的计数?
要在 R 的 data.table 对象列中查找每个类别的计数,我们可以按照以下步骤操作:
首先,创建一个 data.table 对象。
然后,在分组后使用 dplyr 包的 summarise 函数以及 n。
示例
创建 data.table 对象
让我们创建一个如下所示的 data.table 对象:
library(data.table) factor<-sample(c("very low","low","medium","high","very high"),25,replace=TRUE) response<-rnorm(25) DT<-data.table(factor,response) DT
输出
执行上述脚本后,将生成以下输出(由于随机化,此输出会在您的系统上有所不同):
factor response 1: very high -0.14064701 2: high -0.36029663 3: low -0.50825291 4: very high -2.07959316 5: high 0.25578922 6: very high 1.17946264 7: low 1.32803179 8: medium -0.23736325 9: medium -0.07440274 10: very low 0.32669673 11: very low 0.54953485 12: high -0.93197732 13: very high -0.77787846 14: very low 0.63808636 15: very high 0.76008767 16: very high -0.38712279 17: very high -0.64259955 18: high 0.30249791 19: high 0.16984229 20: very low -0.24732679 21: high -0.47456705 22: low 0.08789350 23: low 0.32541943 24: medium -0.27170782 25: high -0.09860207 factor response
查找 data.table 对象中每个类别的计数
使用 dplyr 包的 summarise 函数以及 n 在 data.table 对象 DT 的因子列中查找每个类别的计数:
library(data.table) factor<-sample(c("very low","low","medium","high","very high"),25,replace=TRUE) response<-rnorm(25) DT<-data.table(factor,response) library(dplyr) DT %>% group_by(factor) %>% summarise(count=n())
输出
# A tibble: 5 x 2 factor count <chr> <int> 1 high 7 2 low 4 3 medium 3 4 very high 7 5 very low 4
广告