dez93_2000 dez93_2000 - 1 month ago 11
R Question

Create list using rep() [R]

this is probably really easy but I've been trying & failing to find the solution, & I think I'm trying to fit square pegs in round holes with

lapply
& such.

I have a function in which a subfunction will call a numbered list object. The number will be in a loop & therefore change, and the number & 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)
. BUT:
object = as.list(rep(c(2,6),8))
results in a list of 16 single numbers:
2 6 2 6 2 6 2 6
& so on.

Any ideas how I can force R to create a list of e.g. 8 vectors, rather than e.g. 16 single numbers? I tried
drop=0
but that didn't help, and I'm struggling to get my head around how I would get
lapply
to work.

Thanks in advance!

Answer

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