Make a list of consecutive numbers in R

2.7k views Asked by At

I want to make a list of consecutive numbers like this:

 list(1,2,3,4)

Gives list of four.

Now I don't want to write all numbers, so try:

 list(1:4)

Gives List of length four.

If I want to make a list of four without writing all the numbers what could be the syntax?

Please help, thanks

3

There are 3 answers

2
Val On BEST ANSWER

You can use as.list(1:4)

as.list(1:4)

[[1]] [1] 1

[[2]] [1] 2

[[3]] [1] 3

[[4]] [1] 4

EDIT

or as.list(seq(4))

EDIT #2

Here's a speed comparison using microbenchmark:

microbenchmark(as.list(1:4), as.list(seq(4)), Map(c,1:4), sapply(1:4, list), times=1e6)
Unit: microseconds
              expr   min    lq      mean median     uq      max neval
      as.list(1:4) 1.472 2.088  2.639712  2.314  2.584 32594.44 1e+06
   as.list(seq(4)) 3.934 5.359  6.514579  5.818  6.337 31498.31 1e+06
       Map(c, 1:4) 3.435 5.052  6.243628  5.516  6.041 32628.84 1e+06
 sapply(1:4, list) 6.892 9.358 11.282727 10.009 10.757 34269.70 1e+06
0
dario On

We could use

sapply(1:4, list)
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 4
all.equal(sapply(1:4, list), list(1,2,3,4))
[1] TRUE
0
ThomasIsCoding On

You can try the code with Map

Map(c,1:4)

such that

> Map(c,1:4)
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 4