I want to create a list which is eight times the vector c(2,6)
, i.e. a list of 8 vectors.
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 ...
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)
.
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.
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.
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).
rep(list(c(2,6)),8)
is the answer - thanks to Nicola in comments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With