Counting even numbers from vectror wich contain NA values ?

I've created a vector and set negative values as missing (NA). Now i shoud sum the even numbers from vector, but haven't realised how to do it.

is.double command check's is the vector even?
I've also tried to sum %%2
and the missing values should consider with na.rm=TRUE ?

I would be very gratefull if someone could help me so I would graduate in Schedule :slight_smile:

Hi,
the is.double command test for the double-precision and not if the variable is even or not.
and if you sum directly the %%2values, you will only sum the binary result, which correspond to the number of even and not null values.
So, as a solution, firstly, you can apply the sum on the original vector without converting numbers to NA, for example:

vec = c(-5,4,3,NA,-9,2, NA,1, 20)
sum(vec[vec>0 & !vec%%2], na.rm = T)

in your case, you can do:

sum(vec[!vec%%2], na.rm = T)

good luck.

1 Like

Thank you, i was quite close but not right yet (sum(!is.na(vec)%%2).

I wish you very nice day!

I understand now that you want the count and not the sum, you can use:

sum( !vec%%2, na.rm = T)
1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.