Question: How To Count The Number Of Elements In A Column Other Than 'X' In R
2
Don20 wrote:

I have a column that contains several "NA" while the other are alphanumeric. I want to count the elements that are NOT "NA". I used

``````M1<-length(M11\$DAID[M11\$DAID =="NA"])
``````

to count the NA but

``````NM1<-length(M11\$DAID[M11\$DAID !="NA"])
``````

wouldn't work for non-NA. Thanks for your help

R programming • 110k views
modified 9.3 years ago by Stefano Berri4.1k • written 9.3 years ago by Don20
5
Stefano Berri4.1k wrote:

The problem with your code is that NA are not character, but NA.

``````> a <- c("Kat", "cat", "Kat", NA)
> length(which(a == "Kat"))
 2
>lengthwhichis.na(a)))
 1
> length(which(a != "Kat"))
 1
> length(which(!is.na(a)))
 3
``````

Above, is how you should do it, however

``````> length(which(a != "NA"))
 3
> length(which(a == "NA"))
 0
``````

which might look strange. The first seem to work, the second doesn't. But they are both "wrong".

Basically this happens because in the first case there are three elements that are not character "NA". NA is not a character, so it does not count In the second case, there are no elements that match with character "NA". Once again, NA is not a character, so it does not count.

Further reads: http://cran.r-project.org/doc/manuals/R-intro.html#Missing-values (the whole "book" is worth having in the bookmarks when working with R)

3
Jeremy Leipzig19k wrote:
``````> a<-c(1,2,NA,4)
> lengthwhichis.na(a)))
 1
> length(which(!is.na(a)))
 3
``````

hi Jeremy, what if it was "Kat" rather than NA. is there an opposite for =="kat" (ie count every other element but kat)? Thanks

``````> a <- c("Kat", "cat", "Kat")
length(which(a == "Kat"))
 2
length(which(a != "Kat"))
 1
``````

`NA` are not character, but `NA`, that is, I think, why your code does not work.