简体   繁体   English

如何将间隔作为向量列表?

[英]How to get intervals as a list of vectors?

I have a numeric vector and I need to get the intervals as a list of vectors.我有一个数字向量,我需要将间隔作为向量列表。

I thought it was easy but I'm really struggling to find a good, simple way.我认为这很容易,但我真的很难找到一个好的、简单的方法。

A bad, complex way would be to paste the vector and its lag, and then split the result.一个糟糕的、复杂的方法是粘贴向量及其滞后,然后拆分结果。

Here is the working but ugly reprex:这是有效但丑陋的reprex:

library(tidyverse)
xx = c(1, 5, 10 ,15 ,20)
paste0(lag(xx), "-", xx-1) %>% str_split("-") #nevermind the first one, it cannot really make sense anyway
#> [[1]]
#> [1] "NA" "0" 
#> 
#> [[2]]
#> [1] "1" "4"
#> 
#> [[3]]
#> [1] "5" "9"
#> 
#> [[4]]
#> [1] "10" "14"
#> 
#> [[5]]
#> [1] "15" "19"

Created on 2020-09-06 by the reprex package (v0.3.0)reprex 包(v0.3.0) 于 2020 年 9 月 6 日创建

Is there a cleaner way to do the same thing?有没有更干净的方法来做同样的事情?

You can use Map :您可以使用Map

Map(c, xx[-length(xx)], xx[-1] - 1)

#[[1]]
#[1] 1 4

#[[2]]
#[1] 5 9

#[[3]]
#[1] 10 14

#[[4]]
#[1] 15 19

We can also use lapply iterating over the length of the variable.我们还可以使用lapply迭代变量的长度。

lapply(seq_along(xx[-1]), function(i) c(xx[i], xx[i+1] - 1))

We can use map2 from purrr我们可以使用purrr map2

library(purrr)
map2(xx[-length(xx)], xx[-1] -1, c)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM