Pergunta

You have the following vector which has NA's mixed in. There are no consecutive NA's and the vector is of unknown length. There are always the same number of NA's.

#Data
testvector <- c(NA,rnorm(round(abs(rnorm(1))*10)),NA,rnorm(round(abs(rnorm(1))*10)),NA,rnorm(round(abs(rnorm(1))*10)),NA,rnorm(round(abs(rnorm(1))*10)),NA,rnorm(round(abs(rnorm(1))*10)))

You need to find the number of non-NA values that exist after each NA. This needs to be return as a vector. The length of this vector will equal the number of NA's.

For this vector.

thisvector <- c(NA,rnorm(4),NA,rnorm(5),NA,rnorm(9),NA,rnorm(2),NA,rnorm(6))

What you want is

somefunction(thisvector)
[1] 4 5 9 2 6

How can this be done?

Foi útil?

Solução

Use rle on the output of is.na to get what you want:

x <- rle(is.na(testvector))
x$lengths[!x$values]
## [1] 1 2 5 9 4
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top