我有一个数据帧,其中包含与观察值 1 或 0 相关的值。我想计算 1 的连续出现次数,重置为 0。游程长度编码函数(rle
)看起来它可以完成工作,但我无法将数据转换为所需的格式。我想尝试在不编写自定义函数的情况下执行此操作。在下面的数据中,我在数据框中进行观察,然后我想导出“连续”列并写回数据框。这个链接是一个好的开始 https://stackoverflow.com/questions/9249338/running-sum-on-a-column-conditional-on-value/9249411.
observation continual
0 0
0 0
0 0
1 1
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
1 11
1 12
0 0
0 0
您可以通过几个步骤轻松完成此操作:
x <- rle(mydf$observation) ## run rle on the relevant column
new <- sequence(x$lengths) ## create a sequence of the lengths values
new[mydf$observation == 0] <- 0 ## replace relevant values with zero
new
# [1] 0 0 0 1 2 3 4 5 6 7 8 9 10 11 12 0 0
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)