[R] remove NaN from element in a vector in a list

Hadley Wickham hadley at rice.edu
Tue Sep 27 22:39:31 CEST 2011


>> apply(mt, 1, function(x) x[!is.nan(x)] )
> [[1]]
> [1] 1 3
>
> [[2]]
> [1] 4 5 6

You need to be a little careful with apply:

> mt2 <- matrix(c(1,4,2,5,3,6),2,3)
> apply(mt2, 1, function(x) x[!is.nan(x)] )
     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6

Depending on the input you will get a list or matrix as output.

Hadley

-- 
Assistant Professor / Dobelman Family Junior Chair
Department of Statistics / Rice University
http://had.co.nz/



More information about the R-help mailing list