how to realize countifs function (excel) in R

前端 未结 5 935
面向向阳花
面向向阳花 2020-11-30 08:58

I have a dataset containing 100000 rows of data. I tried to do some countif operations in Excel, but it was prohibitively slow. So I am wondering if this kind o

5条回答
  •  春和景丽
    2020-11-30 09:56

    Easy peasy. Your data frame will look like this:

    df <- data.frame(sex=c('M','F','M'),
                     occupation=c('Student','Analyst','Analyst'))
    

    You can then do the equivalent of a COUNTIF by first specifying the IF part, like so:

    df$sex == 'M'
    

    This will give you a boolean vector, i.e. a vector of TRUE and FALSE. What you want is to count the observations for which the condition is TRUE. Since in R TRUE and FALSE double as 1 and 0 you can simply sum() over the boolean vector. The equivalent of COUNTIF(sex='M') is therefore

    sum(df$sex == 'M')
    

    Should there be rows in which the sex is not specified the above will give back NA. In that case, if you just want to ignore the missing observations use

    sum(df$sex == 'M', na.rm=TRUE)
    

提交回复
热议问题