Hugo Law-koune
Hugo Law-koune

Reputation: 1

Repeat an argument in function

I have a list l and an integer n. I would like to pass l n-times to expand.grid.

Is there a better way than writing expand.grid(l, l, ..., l) with n times l?

Upvotes: 0

Views: 650

Answers (4)

Erdogan CEVHER
Erdogan CEVHER

Reputation: 1609

If the function is wanted to (repeatedly) act on the elements of the list freely (i.e., the list members being unconnected from the defined list itself), the following will be useful:

l <- list(1:5, "s") # A list with numerics and characters
n <- 3 # number of repetitions
expand.grid(unlist(rep(l, n))) # the result is:
   Var1
1     1
2     2
3     3
4     4
5     5
6     s
7     1
8     2
9     3
10    4
11    5
12    s
13    1
14    2
15    3
16    4
17    5
18    s

Upvotes: 0

NJBurgo
NJBurgo

Reputation: 779

I think the easiest way to solve the original question is to nest the list using rep.

For example, to expand the same list, n times, use rep to expand the nested list as many times as necessary (n), then use the expanded list as the only argument to expand.grid.

# Example list
l <- list(1, 2, 3)

# Times required
n <- 3

# Expand as many times as needed
m <- rep(list(l), n)

# Expand away
expand.grid(m)

Upvotes: 0

Qaswed
Qaswed

Reputation: 3879

If the solution by @Phann doesn't fit to your situation, you can try the following "evil trio" solution:

l <- list(height = seq(60, 80, 5), weight = seq(100, 300, 50), sex = c("male", "female"))

n <- 4


eval(parse(text = paste("expand.grid(", 
                  paste(rep("l", times = n), collapse = ","), ")")))

Upvotes: 0

Phann
Phann

Reputation: 1327

The function rep seems to do what you want.

n <- 3 #number of repetitions

x <- list(seq(1,5))
expand.grid(rep(x,n)) #gives a data.frame of 125 rows and 3 columns

x2 <- list(a = seq(1,5), b = seq(6, 10))
expand.grid(rep(x2,n)) #gives a data.frame of 15625 rows and 6 columns

Upvotes: 2

Related Questions