首页 > 解决方案 > 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?

标签: rdata.tablefrequency

解决方案


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

推荐阅读