Q:

find appearance of consecutive phrase in columns

I have the following data frame, describing progression of something from the current state ("0") to 5 years after.
df = structure(list(Prog0to1 = c("different", "different", "same", 
"different", "disappeared", "different", "same", "same", "different", 
"different"), Prog1to2 = c("disappeared", "disappeared", "disappeared", 
"different", "different", "different", "different", "same", "same", 
"Deceased"), Prog2to3 = c("disappeared", "different", "disappeared", 
"same", "disappeared", "same", "different", "different", "disappeared", 
"Deceased"), Prog3to4 = c("different", "same", "disappeared", 
"same", "disappeared", "same", "disappeared", "same", "disappeared", 
"Deceased"), Prog4to5 = c("same", "same", "disappeared", "different", 
"disappeared", "different", "disappeared", "same", "disappeared", 
"Deceased")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-10L))

in df, "same" means that the state of the previous year is the same as the current year.
I would like to count, for each row, how many times there was a consecutive "same", and if there are two such periods, take the median of how many times "same" appeared consecutively.
So the output vector should be:
v = c(1, 2, 1, 2, 0, 2, 1, 2, 1, 0),

where the 8th value is the median between 2 and 2, which is 2 (there are two periods of "same" separated by "different").
How can I achieve this?

A:

We could use apply with rle and take median of lengths where values is "same".
vals <- apply(df == "same", 1, function(x) median(with(rle(x), lengths[values])))
vals
#[1]  1  2  1  2 NA  2  1  2  1 NA

If you want 0's instead of NAs
replace(vals, is.na(vals), 0)
#[1] 1 2 1 2 0 2 1 2 1 0

