Splits the values in a numeric matrix column-wise into sequences of non-missing values.

split_by_NAs(x)

Arguments

x

A vector or matrix.

Value

A matrix containing a column for each run of non-missing values in

x. The number of rows is equal to the longest run of non-missing values in x and will therefore be at most nrow{x}. The matrix is padded with NA values at the end of each column, where necessary.

The returned object has an attribute called split_by_NAs_done

whose value is TRUE, so that in programming one can avoid calling

split_by_NAs more than once.

Details

For each column in x, split_by_NAs finds runs of values that contain no missing values and assigns them to a column in the matrix that is returned. Different columns are treated separately. If there are no missing values in a column then that column appears unmodified in the output matrix. Please see the Examples for illustrations.

Examples

# Create a simple numeric matrix and insert some NAs
x <- matrix(1:50, 10, 5)
x[c(3, 8), 1] <- NA
x[c(1:2, 5, 10), 3] <- NA
x[1:3, 4] <- NA
x[7:10, 5] <- NA
x
#>       [,1] [,2] [,3] [,4] [,5]
#>  [1,]    1   11   NA   NA   41
#>  [2,]    2   12   NA   NA   42
#>  [3,]   NA   13   23   NA   43
#>  [4,]    4   14   24   34   44
#>  [5,]    5   15   NA   35   45
#>  [6,]    6   16   26   36   46
#>  [7,]    7   17   27   37   NA
#>  [8,]   NA   18   28   38   NA
#>  [9,]    9   19   29   39   NA
#> [10,]   10   20   NA   40   NA

res <- split_by_NAs(x)
res
#>       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
#>  [1,]    1    4    9   11   23   26   34   41
#>  [2,]    2    5   10   12   24   27   35   42
#>  [3,]   NA    6   NA   13   NA   28   36   43
#>  [4,]   NA    7   NA   14   NA   29   37   44
#>  [5,]   NA   NA   NA   15   NA   NA   38   45
#>  [6,]   NA   NA   NA   16   NA   NA   39   46
#>  [7,]   NA   NA   NA   17   NA   NA   40   NA
#>  [8,]   NA   NA   NA   18   NA   NA   NA   NA
#>  [9,]   NA   NA   NA   19   NA   NA   NA   NA
#> [10,]   NA   NA   NA   20   NA   NA   NA   NA
#> attr(,"split_by_NAs_done")
#> [1] TRUE

# An example of a character matrix
x <- matrix(c(letters, letters[1:18]), 11, 4)
x[c(1:2, 5:11), 2] <- NA
x[c(2:4, 6:11), 3] <- NA
x[1:10, 4] <- NA

res <- split_by_NAs(x)
res
#>       [,1] [,2] [,3] [,4] [,5]
#>  [1,] "a"  "n"  "w"  "a"  "r" 
#>  [2,] "b"  "o"  NA   NA   NA  
#>  [3,] "c"  NA   NA   NA   NA  
#>  [4,] "d"  NA   NA   NA   NA  
#>  [5,] "e"  NA   NA   NA   NA  
#>  [6,] "f"  NA   NA   NA   NA  
#>  [7,] "g"  NA   NA   NA   NA  
#>  [8,] "h"  NA   NA   NA   NA  
#>  [9,] "i"  NA   NA   NA   NA  
#> [10,] "j"  NA   NA   NA   NA  
#> [11,] "k"  NA   NA   NA   NA  
#> attr(,"split_by_NAs_done")
#> [1] TRUE