Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create list of vectors using rep()

I want to create a list which is eight times the vector c(2,6), i.e. a list of 8 vectors.

  • WRONG: object = as.list(rep(c(2,6),8)) results instead in a list of 16 single numbers: 2 6 2 6 2 6 2 6 ...
  • I tried drop=0 but that didn't help, and I can't get lapply to work.

(My context: I have a function in which a subfunction will call a numbered list object. The number will be in a loop and therefore change, and the number and loop size is dependent on user values so I don't know what it'll be. If the user doesn't enter a list of vector values for one of the variables, I need to set a default.

The subfunction is expecting e.g. c(2,6) The subfunction is currently looping 8 times so I need a list which is eight times c(2,6).

like image 537
dez93_2000 Avatar asked Mar 01 '16 23:03

dez93_2000


People also ask

What does Rep () do in R?

In simple terms, rep in R, or the rep() function replicates numeric values, or text, or the values of a vector for a specific number of times.

Is it possible to create a list of vectors?

In this article, we will study how to create a list consisting of vectors as elements and how to access, append and delete these vectors to lists. list() function in R creates a list of the specified arguments. The vectors specified as arguments in this function may have different lengths.

How do I replicate a list in R?

The replication of list of a list can be created by using rep function. For example, if we have a list called x and we want to create five times replicated list of this list then we can use the code rep(list(x),5).


1 Answers

rep(list(c(2,6)),8) is the answer - thanks to Nicola in comments.

like image 143
dez93_2000 Avatar answered Oct 15 '22 15:10

dez93_2000