2016-08-02 36 views
0

我有一個列表l和一個整數n。我想通過ln次到expand.grid在函數中重複參數

有沒有比寫expand.grid(l, l, ..., l) n次更好的方法l

+0

您是否想要展開原始對象的列表?然後看我的答案,一個更復雜的對象列表可以用@ Qaswed的回答來解決 – NJBurgo

回答

2

功能rep似乎做你想做的。

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 
0

如果@Phann解決方案不適合你的情況,你可以試試下面的「evil trio」的解決方案:

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 = ","), ")"))) 
+0

我喜歡這個,但是我不認爲**它回答了setters問題。雖然setters問題可以用這種方式解釋。 – NJBurgo

0

我認爲,解決原來的問題最簡單的方法是使用rep嵌套列表。

例如,要展開n次相同的列表,使用rep根據需要多次展開嵌套列表(n),然後使用展開的列表作爲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) 
0

如果該函數要在列表的元素(重複地)動作自如(即,列表成員是從所定義的列表本身未連接),以下將是有用的:

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