r - R extracting the frequencies
问题描述
I am trying to get the frequencies but my ids are repeating. Here is a sample data:
id <- c(1,1,2,2,3,3)
gender <- c("m","m","f","f","m","m")
score <- c(10,5,10,5,10,5)
data <- data.frame("id"=id,"gender"=gender, "score"=score)
> data
id gender score
1 1 m 10
2 1 m 5
3 2 f 10
4 2 f 5
5 3 m 10
6 3 m 5
I would like to get the frequencies of the gender categories but I have repeating ids. When I run this code below:
gender<-as.data.frame(table(data$gender))
> gender
Var1 Freq
1 f 2
2 m 4
The frequency should be female = 1, male =2. it should look like this below:
> gender
Var1 Freq
1 f 1
2 m 2
How can I get this considering the id information?
解决方案
You can use data.table::uniqueN
to count the number of unique ids per gender group
library(data.table)
setDT(data)
data[, .(Freq = uniqueN(id)), gender]
# gender Freq
# 1: m 2
# 2: f 1
推荐阅读
- c - OpenSSL C API:使用 CRL 进行证书链验证
- php - 将 api 路由到 Laravel 中的控制器
- excel - VBA:在 For 循环中的 IF/Then 语句中插入行
- visual-studio-2017 - 图片幻灯片显示在我的 vs 工作室的背景中
- c++ - 我的程序造反了?未进行更改
- javascript - 使用本地计算机上的 Jquery 重新加载或刷新页面
- javascript - 导入 React:意外的标识符“React”。import call 只需要一个参数。”
- opencl - 如何编译包含 GCN 卡内联汇编的 .cl 文件?
- jquery - jQuery UI 的可拖动文本框
- c++ - QPixmap() 的 std::bad_alloc 问题