costebk08
costebk08

Reputation: 1359

frequency and percentage counts across multiple columns

I have data that looks like:

print(dat)
i1  i2  i3  i4
 0   1   1   0
NA   1   1   1
 0   0   0   1
 1   1   1   1

My goal is get three pieces of information ideally through some combination of a function and sapply: the number of ones, the number of 0s, and the percentage of non-NAs that are 1s. So for example the ideal result here would be something like:

function(dat)
0  1   percentage
5  10      66.7

Thanks!

Upvotes: 2

Views: 81

Answers (1)

agstudy
agstudy

Reputation: 121568

Here one option:

c(sum(mat==0,na.rm=TRUE),
  sum(mat==1,na.rm=TRUE),
  round(sum(mat==1,na.rm=TRUE)/sum(!is.na(mat))*100,1))

## 5.0 10.0 66.7

Upvotes: 5

Related Questions