R: Is there a way to count the number of consecutive numbers in each row?

主宰稳场 提交于 2021-02-11 04:26:22

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!