[R] length with missing values

Barry Rowlingson B.Rowlingson at lancaster.ac.uk
Fri Oct 15 13:28:01 CEST 2004


Luis Rideau Cruz wrote:
> R-help
> 
> I have a martix with missing values( in which I want the sample size by
> column)
> When I :
> 
> apply(matrix,2,length)
> 
> I get the length of the vector regardless of missing values.
> I can't pass an argument to length in apply.
> 
> Alternatively I could 
> 
> ifelse ( is.na ( matrix [, "columns in matrix " ] ) , 0 , 1)
> 
> Is there any easier way?
> 

  Firstly, dont call your matrix 'matrix'. Would you call your dog 
'dog'? Anyway, it might clash with the function 'matrix'.

  > m
      [,1] [,2] [,3] [,4]
[1,]    1   NA    7   10
[2,]    2   NA    8   11
[3,]    3    6    9   NA

Here's one way:

  > apply(m,2,function(x){sum(!is.na(x))})
  [1] 3 1 3 2

  you can supply a function to apply() which gets a column (in this 
case) at a time. It returns a scalar.

  Another way is to apply 'sum' to the matrix of 0s and 1s got from 
!is.na(m):

  > apply(!is.na(m),2,sum)
  [1] 3 1 3 2


Doubtless greater R-souls than me will come up with faster and better ways.




More information about the R-help mailing list