Search code examples
rdata.tablefrequency

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?


Solution

  • In base R

    rowSums(table(data$gender,data$id)!=0)
    f m 
    1 2