How To Count The Number Of Elements In A Column Other Than 'X' In R
2
2
Entering edit mode
13.5 years ago
Don ▴ 20

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 • 134k views
ADD COMMENT
5
Entering edit mode
13.5 years ago

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

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

Above, is how you should do it, however

> length(which(a != "NA")) 
[1] 3
> length(which(a == "NA")) 
[1] 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)

ADD COMMENT
3
Entering edit mode
13.5 years ago
> a<-c(1,2,NA,4)
> lengthwhichis.na(a)))
[1] 1
> length(which(!is.na(a)))
[1] 3
ADD COMMENT
0
Entering edit mode

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

ADD REPLY
0
Entering edit mode
> a <- c("Kat", "cat", "Kat")
length(which(a == "Kat"))
[1] 2
length(which(a != "Kat"))
[1] 1

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

ADD REPLY

Login before adding your answer.

Traffic: 1585 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6