从R中n个连续值不为0的向量创建向量列表 [英] Create a list of vectors from a vector where n consecutive values are not 0 in R

查看:49
本文介绍了从R中n个连续值不为0的向量创建向量列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个向量:

a = sample(0:3, size=30, replace = T)
 [1] 0 1 3 3 0 1 1 1 3 3 2 1 1 3 0 2 1 1 2 0 1 1 3 2 2 3 0 1 3 2

我想要的是一个向量列表,其中所有元素都被n 0分隔.因此,在这种情况下,如果n = 0(连续值之间不能有0),则得出:

What I want to have is a list of vectors with all the elements that are separated by n 0s. So in this case, with n = 0 (there can't be any 0 between the consecutive values), this would give:

res = c([1,3,3], [1,1,1,3,3,2,1,1,3], [2,1,1,2]....)

但是,如果我将n参数设置为2,那么我想灵活地控制n参数,就像这样:

However, I would like to control the n-parameter flexible to that if I would set it for example to 2, that something like this:

b = c(1,2,0,3,0,0,4)

仍然会得到这样的结果

res = c([1,2,3],[4])

我尝试了很多在for循环中使用while循环的方法,同时尝试计算0的数量.但我只是无法实现.

I tried a lot of approaches with while loops in for-loops while trying to count the number of 0s. But I just could not achieve it.

更新

我试图在更现实的环境中发布问题:根据中的连续计数灵活地计算列R

I tried to post the question in a more real-world setting here: Flexibly calculate column based on consecutive counts in another column in R

谢谢大家的帮助.我似乎只是凭有限的知识似乎无法设法将您的帮助付诸实践.

Thank you all for the help. I just don't seem to manage put your help into practice with my limited knowledge..

推荐答案

这是基本的R选项,在一般情况下使用 rle + split ,即 b 不限于 0 3 .

Here is a base R option using rle + split for general cases, i.e., values in b is not limited to 0 to 3.

with(
  rle(with(rle(b == 0), rep(values & lengths == n, lengths))),
  Map(
    function(x) x[x != 0],
    unname(split(b, cut(seq_along(b), c(0, cumsum(lengths))))[!values])
  )
)

给出(假设 n = 2 )

[[1]]
[1] 1 2 3

[[2]]
[1] 4


如果您的值介于ragne 0 9 之间,则可以尝试以下代码


If you have values within ragne 0 to 9, you can try the code below

lapply(
  unlist(strsplit(paste0(b, collapse = ""), strrep(0, n))),
  function(x) {
    as.numeric(
      unlist(strsplit(gsub("0", "", x), ""))
    )
  }
)

这也给

[[1]]
[1] 1 2 3

[[2]]
[1] 4

这篇关于从R中n个连续值不为0的向量创建向量列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆