Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count rows between NA's

Tags:

r

i'm trying to get a specific count from a previously created result set. I need a count of rows between rows that contain NA's. An aggregation of values of these rows are not of interest, only the count.

Below a quite simplified example which hopefully better explains what i'm talking about. At left hand the actual data and at right hand the desired result.

+------+-------+---+------+--------+
| TIME | Value | - | TIME | Result |
+------+-------+---+------+--------+
|   10 | NA    | - |   20 |      2 |
|   20 | 0     | - |   60 |      3 |
|   30 | 1     | - |      |        |
|   40 | NA    | - |      |        |
|   50 | NA    | - |      |        |
|   60 | 30    | - |      |        |
|   70 | 68    | - |      |        |
|   80 | 0     | - |      |        |
|   90 | NA    | - |      |        |
+------+-------+---+------+--------+

Any comments are welcome. In case additional input is needed please leave a message.

like image 356
kukuk1de Avatar asked Nov 05 '14 16:11

kukuk1de


1 Answers

In order to make my answer complete here a modified version:

d <- data.frame( TIME = seq(10, 90, by = 10), Value = c(NA, 0, 1, NA, NA, 30, 68, 0, NA))


aux <- rle(as.numeric((!is.na(d[,2]))))

cbind(TIME = d[cumsum(aux$lengths)[which(aux$values == 1)] - aux$lengths[aux$values == 1] +1, 1],
Result = rle(is.na(d$Value))$lengths[!rle(is.na(d$Value))$values])
     TIME Result
[1,]    2     20
[2,]    3     60
like image 107
DatamineR Avatar answered Oct 10 '22 21:10

DatamineR