0

Is there a quickest way to make a list as below in R? There are numbers 1 through 18, and two elements are grouped.

list(c(1,2),c(3,4),c(5,6),c(7,8),c(9,10),c(11,12),c(13,14),c(15,16),c(17,18))
Soon
  • 491
  • 3
  • 16

2 Answers2

2

We can do this with split using a grouping variable created with gl

unname(split(v1, as.integer(gl(length(v1), 2, length(v1)))))

Or use %/% to create the grouping variable

unname(split(v1, (seq_along(v1)-1) %/% 2))

data

v1 <- 1:18
akrun
  • 874,273
  • 37
  • 540
  • 662
2

The OP has asked for the quickest way to make the list. I suppose "quick" is meant in terms of typing code, not speed of execution.

The list of vectors can be created using a combination of lapply() and seq() :

lapply(seq(1, 18, by = 2), seq, length.out = 2)

A more concise variant of this approach would be

lapply(1:9, function(x) 2*x + -1:0)

This appears to me much more straight forward than splitting which requires to introduce a grouping variable.

Uwe
  • 41,420
  • 11
  • 90
  • 134