magwabat
magwabat

Reputation: 11

Count the frequency of concecutive zeros in a every time they appear in a each row

I have this dataframe and would like to compute a count of zero sequences every time they appear in a row so that the output would be A: 2 4, B:1 2 1, C:2 5, D: 2 3, E: 1 1

df <- data.frame(
A=c(1,  0,  0,  1,  1,  0,  0,  0,  0), 
B=c(0,  1,  1,  0,  0,  1,  0,  1,  1),
C=c(0,  0,  1,  1,  0,  0,  0,  0,  0), 
D=c(0,  0,  1,  1,  1,  1,  0,  0,  0),
E=c(1,  0,  1,  1,  1,  1,  0,  1,  1)
)

Upvotes: 0

Views: 46

Answers (1)

akrun
akrun

Reputation: 887098

We may use rle by looping over the columns of the data.frame and get the lengths of the 0 values in base R

lapply(df1, function(x) with(rle(x), lengths[!values]))

-output

$A
[1] 2 4

$B
[1] 1 2 1

$C
[1] 2 5

$D
[1] 2 3

$E
[1] 1 1

data

df1 <- structure(list(A = c(1, 0, 0, 1, 1, 0, 0, 0, 0), B = c(0, 1, 
1, 0, 0, 1, 0, 1, 1), C = c(0, 0, 1, 1, 0, 0, 0, 0, 0), D = c(0, 
0, 1, 1, 1, 1, 0, 0, 0), E = c(1, 0, 1, 1, 1, 1, 0, 1, 1)), row.names = c(NA, 
-9L), class = "data.frame")

Upvotes: 2

Related Questions