Question: How To Count The Number Of Elements In A Column Other Than 'X' In R
2
gravatar for Don
6.9 years ago by
Don20
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 • 82k views
ADD COMMENTlink modified 6.9 years ago by Stefano Berri4.0k • written 6.9 years ago by Don20
5
gravatar for Stefano Berri
6.9 years ago by
Stefano Berri4.0k
Cambridge, UK
Stefano Berri4.0k wrote:

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 COMMENTlink modified 6.9 years ago • written 6.9 years ago by Stefano Berri4.0k
3
gravatar for Jeremy Leipzig
6.9 years ago by
Philadelphia, PA
Jeremy Leipzig17k wrote:

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

ADD COMMENTlink written 6.9 years ago by Jeremy Leipzig17k

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 REPLYlink written 6.9 years ago by Don20

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 REPLYlink written 6.9 years ago by Stefano Berri4.0k
Please log in to add an answer.

Help
Access

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 1411 users visited in the last hour