Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Length of columns excluding NA in r

Tags:

r

Suppose that I have a data.frame as follows:

   a  b c
1  5 NA 6
2 NA NA 7
3  6  5 8

I would like to find the length of each column, excluding NA's. The answer should look like

a b c 
2 1 3 

So far, I've tried:

 !is.na()                  # Gives TRUE/FALSE
 length(!is.na())          # 9 -> Length of the whole matrix
 dim(!is.na())             # 3 x 3 -> dimension of a matrix
 na.omit()                 # removes rows with any NA in it.

Please tell me how can I get the required answer.

like image 654
Ay_M Avatar asked Jul 06 '13 07:07

Ay_M


People also ask

How do you find the length of a vector with NA in R?

To get the size (number of elements) of a vector in R use the length() function. This length() function returns the number of elements in a vector without ignoring NA values. To get the size without NA values use na.

What does Na exclude do in R?

action settings within R include: na. omit and na. exclude: returns the object with observations removed if they contain any missing values; differences between omitting and excluding NAs can be seen in some prediction and residual functions.

How do I find the length of a column in R?

You can use the length() function in R to calculate the length of vectors, lists, and other objects.


3 Answers

Or faster :

colSums(!is.na(dat))
a b c 
2 1 3 
like image 195
agstudy Avatar answered Oct 18 '22 19:10

agstudy


> apply(dat, 2, function(x){sum(!is.na(x))})
a b c 
2 1 3 
like image 43
user1609452 Avatar answered Oct 18 '22 17:10

user1609452


Though the sum is probably a faster solution, I think that length(x[!is.na(x)]) is more readable.

like image 2
Dan Chaltiel Avatar answered Oct 18 '22 17:10

Dan Chaltiel