0

我有一列很长的数字。我希望 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 列。

谢谢!

4

1 回答 1

1

我不知道您如何期望拥有不同长度的列。用NA?

此解决方案使用rle并将向量拆分为 a 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
于 2013-04-18T12:28:39.510 回答