我有一长串数字。我想让R每次从零变化时创建一个新列。 专栏的例子:
90.1194354
87.94788274
80.34744843
64.06080347
30.40173724
0
0
0
0
0
16.28664495
23.88707926
29.31596091
48.85993485
13.02931596
0
0
0
7.600434311
20.62975027
29.31596091
32.5732899
对于这个例子,我想获得3列。
谢谢!
答案 0 :(得分:1)
我不知道您希望如何使用不同长度的列。用NA
填充它们?
此解决方案使用rle
并将向量拆分为list
:
temp <- c(90.1194354, 87.94788274, 80.34744843, 64.06080347, 30.40173724,
0, 0, 0, 0, 0, 16.28664495, 23.88707926, 29.31596091, 48.85993485,
13.02931596, 0, 0, 0, 7.600434311, 20.62975027, 29.31596091,
32.5732899)
x <- rle(temp == 0)
split(temp, rep(seq_along(x$lengths), times = x$lengths))[c(TRUE, FALSE)]
# $`1`
# [1] 90.11944 87.94788 80.34745 64.06080 30.40174
#
# $`3`
# [1] 16.28664 23.88708 29.31596 48.85993 13.02932
#
# $`5`
# [1] 7.600434 20.629750 29.315961 32.573290