Nice Girl Nice Girl - 1 month ago 6
R Question

how to get the count number by condition in r?

summary(as.factor(qanswer$q41))
1 B C D E NA's
112 66 127 45 30 896


I just want to get the number of 1,which is 112.then i tried:

length(qanswer$q41[qanswer$q41==1])
[1] 1008
> length(qanswer$q41[qanswer$q41=='1'])
[1] 1008
> length(qanswer$q41[qanswer$q41=='A'])
[1] 896
> length(qanswer$q41[qanswer$q41=='B'])
[1] 962


I made a function:

x<-function(column){sum(column=='1',na.rm = TRUE)/sum(column,na.rm = TRUE)}
> x(qanswer$q41)
Error in sum(column, na.rm = TRUE) :
invalid 'type' (character) of argument


what's the problem?

Answer

We can use sum

sum(qanswer$q41==1, na.rm = TRUE)

As there are NA values in the 'q41' column, the == returns NA for those NA elements and by subsetting qanswer$q41[qanswer$q41==1], the length will also include the 896 NAs, i.e.

896+ 112 = 1008

Instead, we need to make sure that the NAs are either removed (na.rm=TRUE) in the sum or use !is.na if we wanted to try with length

length(qanswer$41[qanswer$q41==1 & !is.na(qanswer$q41)])