Home > Back-end >  Splitting a vector of values into consecutive segments
Splitting a vector of values into consecutive segments

Time:12-15

If I have a vector:

vec <- c(1,2,3,4,5)

I want to split it into the following data frame of consecutive segments:

x    xend
1    2
2    3
3    4
4    5

I could do it using a loop:

df <- NULL
for (i in 1:(length(vec) - 1)) {
  df <- rbind(df, data.frame(x = vec[i], xend = vec[i   1]))
}

But is there a function in base R that does the job?

CodePudding user response:

You could do:

vec <- c(1,2,3,4,5)

data.frame(
  x = vec[-length(vec)],
  xend = vec[-1]
)
#>   x xend
#> 1 1    2
#> 2 2    3
#> 3 3    4
#> 4 4    5

CodePudding user response:

library(dplyr)

data.frame(x = vec) %>% 
  mutate(xend = lead(x)) %>% 
  filter(!is.na(xend))
  •  Tags:  
  • r
  • Related