Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating lists in R with patterns related to the entry number

Tags:

list

r

Is there a smart way to generate a list like the one below in R using perhaps lapply() or other more extrapolable procedures?

ones   =   c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
twos   =   c(1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1)
threes =   c(1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0)
fours  =   c(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0)
fives  =   c(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)
l = list(ones, twos, threes, fours)

[[1]]
 [1] 1 1 1 1 1 1 1 1 1 1 1

[[2]]
 [1] 1 0 1 0 1 0 1 0 1 0 1

[[3]]
 [1] 1 0 0 1 0 0 1 0 0 1 0

[[4]]
 [1] 1 0 0 0 1 0 0 0 1 0 0

These correspond to polynomials coefficients in generating functions for partitions.

The first list is for ones and so the counting is in steps of 1 integer at a time; hence the vector 1,1,1,1,1,1,1,... In the entry [[2]] we have the twos, and we are counting by 2's starting at 0, skipping the 1 (coded as 0). In [[3]] we are counting by 3's: zero, three, six, nine, etc.

like image 582
Antoni Parellada Avatar asked Mar 11 '23 04:03

Antoni Parellada


1 Answers

A fairly straightforward way in base R is

lapply(seq(0L, 5L), function(i) rep(c(1L, integer(i)), length.out=11L))
[[1]]
 [1] 1 1 1 1 1 1 1 1 1 1 1

[[2]]
 [1] 1 0 1 0 1 0 1 0 1 0 1

[[3]]
 [1] 1 0 0 1 0 0 1 0 0 1 0

[[4]]
 [1] 1 0 0 0 1 0 0 0 1 0 0

[[5]]
 [1] 1 0 0 0 0 1 0 0 0 0 1
  • seq(0L, 5L) produces the vector 0 through 5, an equivalent would be seq_len(5L)-1L, which is faster for creation of large vectors.
  • c(1L, integer(i)) produces the inner, repeated part of the 0-1 vectors, which rep repeats according to the desired length (here 11) using the length.out argument.
  • lapply and function(i) allow the number of 0s to increase as we loop through the vector.
like image 127
lmo Avatar answered May 07 '23 09:05

lmo