r: how to partition a list or vector into pairs at an offset of 1

866 views Asked by At

sorry for the elementary question but I need to partition a list of numbers at an offset of 1. e.g., i have a list like:

c(194187, 193668, 192892, 192802 ..)

and need a list of lists like:

c(c(194187, 193668), c(193668, 192892), c(192892, 192802)...)

where the last element of list n is the first of list n+1. there must be a way to do this with split() but I can't figure it out in mathematica, the command i need is Partition[list,2,1]

2

There are 2 answers

0
akrun On

Here is an option using base R to create a vector of elements

v1 <- rbind(x[-length(x)], x[-1])
c(v1)
#[1] 194187 193668 193668 192892 192892 192802

If we need a list

split(v1, col(v1))

data

x <- c(194187, 193668, 192892, 192802);
0
Hardik Gupta On

You can try like this, using zoo library

library(zoo)

x <- 1:10     # Vector of 10 numbers
m <- rollapply(data = x, 2, by=1, c)    # Creates a Matrix of rows = n-1, each row as a List
l <- split(m, row(m))   #splitting the matrix into individual list

Output:

> l
$`1`
[1] 1 2

$`2`
[1] 2 3

$`3`
[1] 3 4