Tianjian Qin
Tianjian Qin

Reputation: 631

Splitting a vector of values into consecutive segments

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?

Upvotes: 1

Views: 38

Answers (2)

Vin&#237;cius F&#233;lix
Vin&#237;cius F&#233;lix

Reputation: 8811

library(dplyr)

data.frame(x = vec) %>% 
  mutate(xend = lead(x)) %>% 
  filter(!is.na(xend))

Upvotes: 3

stefan
stefan

Reputation: 124148

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

Upvotes: 4

Related Questions