Dan Chaltiel
Dan Chaltiel

Reputation: 8523

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:

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)

Is there a cleaner way to do the same thing?

Upvotes: 2

Views: 62

Answers (2)

akrun
akrun

Reputation: 887881

We can use map2 from purrr

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

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389265

You can use 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(seq_along(xx[-1]), function(i) c(xx[i], xx[i+1] - 1))

Upvotes: 4

Related Questions