Pergunta

I have an R data frame which is just 1 row and looks like so:

x1 x2 x3 x4 x5 x6 x7 x8 x9 x10
 1  1  1  1  0  1  0  1  0  0

I want to know how many 1s there are in a row starting from the first position. So this would be 4.

More examples:

(Example 1)

x1 x2 x3 x4 x5 x6 x7 x8 x9 x10
 0  1  1  1  0  1  0  1  0  0

would be 0 because the first position isn't even a 1.

(Example 2)

x1 x2 x3 x4 x5 x6 x7 x8 x9 x10
 1  0  1  1  0  1  0  1  0  0

would be 1.

How can I implement this?

numInStreakAtBeginning = function(row) {

}

Additionally, how can I implement a method that looks for the largest streak regardless of where it starts? For example,

x1 x2 x3 x4 x5 x6 x7 x8 x9 x10
 1  0  1  1  1  1  0  1  0  0

would be 3.

Foi útil?

Solução

Function that returns a list of length 2, first element of the list is the length of the starting streak of 1's, the second element is the length of the longest streak of 1's.

test <- as.data.frame(matrix(rbinom(20, 1, 0.5), nrow=1))

numInStreakAtBeginning <- function(row){
    runs <- rle(row[1,]) # convert to vector
    retList <- list() # store output

    if(!runs$values[1]){ # if the first value is 0, the length of the first streak is 0
        retList$firstStreak <- 0
    }else{
        retList$firstStreak <- runs$lengths[1] # if the first value is not 0, return length of first streak
    }

    retList$longestStreak <- max(runs$lengths[runs$values==1L]) # the longest streak of 1's, regardless of starting point

    return(retList)
}

numInStreakAtBeginning(test)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top