Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of elements meeting criteria in columns with NA values

Tags:

r

na

sum

I've got a matrix with "A", "B" and NA values, and I would like to count the number of "A" or "B" or NA values in every column.

sum(mydata[ , i] == "A")

and

sum(mydata[ , i] == "B")

worked fine for columns without NA. For columns that contain NA I can count the number of NAs with sum(is.na(mydata[ , i]). In these columns sum(mydata[ , i] == "A") returns NA as a result instead of a number.

How can i count the number of "A" values in columns which contain NA values?

Thanks for your help!

Example:

> mydata
    V1  V2  V3  V4 
V2 "A" "A" "A" "A"
V3 "A" "A" "A" "A"
V4 "B" "B" NA  NA 
V5 "A" "A" "A" "A"
V6 "B" "A" "A" "A"
V7 "B" "A" "A" "A"
V8 "A" "A" "A" "A"

sum(mydata[ , 2] == "A")
# [1] 6

sum(mydata[ , 3] == "A")
# [1] NA

sum(is.na(mydata[ , 3]))
# [1] 1
like image 238
sztup Avatar asked Jan 17 '23 03:01

sztup


2 Answers

The function sum (like many other math functions in R) takes an argument na.rm. If you set na.rm=TRUE, R removes all NA values before doing the calculation.

Try:

sum(mydata[,3]=="A", na.rm=TRUE)
like image 73
Andrie Avatar answered Feb 07 '23 22:02

Andrie


Not sure if this is what you are after. RnewB too so check if this working. Difference between the number of rows and your number of rows will tell you number of NA items.

colSums(!is.na(mydata))
like image 45
InMktgWeTrust Avatar answered Feb 08 '23 00:02

InMktgWeTrust