本文介绍了从向量中提取连续序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为 v 的向量,其中包含正值和负值以及零.问题是,如何提取(在一个列表中)所有连续的正数序列,即用零分隔的正数序列.
I have a vector called v with positive and negative values as well as zeros. The question is, how to extract (in a list) all the continuous sequences of positive numbers, that is the sequences of positive numbers separated by zeros.
这是 v:
v <- c(-75.09619, -38.31229, 0, 57.17792, 65.55923, 108.52735, 104.29929, 32.47125,0, 0, 0, 0, -26.65008, -49.48638, -79.60670,-90.55343, -34.60761, 0, 21.48842, 38.83820, 42.28727, 0)
输出必须类似于:
[1] 57.17792, 65.55923, 108.52735, 104.29929, 32.47125
[2] 21.48842 , 38.83820, 42.28727
有什么想法吗?
推荐答案
你可以试试:
indices <- which(v[v>=0]==0)
x <- Map(function(x,y) setdiff(v[v>=0][(y+1):(x-1)],0),
indices[2:length(indices)],
indices[1:(length(indices)-1)])
x[vapply(x,length,1L)>0]
#[[1]]
#[1] 57.17792 65.55923 108.52735 104.29929 32.47125
#[[2]]
#[1] 21.48842 38.83820 42.28727
我做了什么:
- 从由
v
的 >=0 值形成的向量中取出 0 位置 - 使用
Map
函数,可以提取两个零之间的向量部分 - 最后一行的目的是从结果中去除没有值的序列(例如,如果原始向量中有两个或多个零的序列)
- took the 0 position out of the vector formed with the >=0 values of
v
- with the
Map
function, you can extract the part of the vector between two zeros - the last line's purpose is to strip from the result the sequences without values (if for instance there are sequences of two or more zeroes in the original vector)
这篇关于从向量中提取连续序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!