Skip to content

Split a vector by NA's - is there a better solution then a loop ?

7 messages · Tal Galili, Romain Francois, Henrique Dallazuanna +3 more

#
Maybe this :

 > foo <- function( x ){
+   idx <- 1 + cumsum( is.na( x ) )
+   not.na <- ! is.na( x )
+   split( x[not.na], idx[not.na] )
+ }
 > foo( x )
$`1`
[1] 2 1 2

$`2`
[1] 1 1 2

$`3`
[1] 4 5 2 3

Romain

Le 29/04/10 09:42, Tal Galili a ?crit :

  
    
#
On Thu, Apr 29, 2010 at 1:27 PM, Henrique Dallazuanna <wwwhsd at gmail.com> wrote:
One thing none of the solutions so far do (except I haven't tried
Tal's original code) is insert an empty group between adjacent NA
values, for example in:

 x = c(1,2,3,NA,NA,4,5,6)

 > split(x, replace(cumsum(is.na(x)), is.na(x), -1))[-1]
$`0`
[1] 1 2 3

$`2`
[1] 4 5 6

Maybe this never happens in Tal's case, or it's not what he wanted
anyway, but I thought I'd point it out!

Barry
#
On Thu, 29 Apr 2010, Barry Rowlingson wrote:

            
The ever useful rle() helps
$`1`
[1] 1 2 3

$`2`
[1] 4 5 6


Chuck
Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901