问题
I'm wondering if there's a way to count the number of consecutive numbers in each row. Ideally, the output will be in column V6 and count the number of consecutive numbers in columns V1-V5.
For example, Row 1 - 1, 2, 3, 4, 5 since there are 5 consecutive numbers, the output will be 5. I've attached the dataset that I have below for your reference.
Thanks.
enter image description here
回答1:
Here is an option where we get the difference between alternate columns by removing the first column, last column, convert to a logical matrix (== 1) and get the rowSums
rowSums((df1[-1] - df1[-ncol(df1)]) == 1) + 1
#[1] 5 4 4 4 4 4 4 4 4 4
data
df1 <- data.frame(V1 = 1, V2 = 2, V3 = 3, V4 = 4, V5 = 5:14)
来源:https://stackoverflow.com/questions/60326939/r-is-there-a-way-to-count-the-number-of-consecutive-numbers-in-each-row