2013-10-03 23 views
0

我在循環中遇到了一些棘手的挑戰,我想在r中做更快的事情。 如何將一系列小型計算分配給一系列變量?例如:如何爲r中的變量序列分配一系列計算

fex1 = rbind(ben1,mal1) 
fex2 = rbind(ben2,mal2) 
fex3 = rbind(ben3,mal3) 
.... 
.... 
fex40 = rbind(ben40,mal40) 

其中賁(i)和MAL(i)是由7 13矩陣序列1:40和FEX(ⅰ)也變量名1:40的序列。基本上,我已經將一些數據分成了各種各樣的摺疊,並且想要拆分分割數據集的組合以執行一些其他計算。我已經使用lapply來循環rbind和其他函數,但是我如何實現這個任務,應用像rbind這樣的函數,並將這些值存儲在一系列變量中?

謝謝。

+3

爲什麼你希望他們作爲獨立的對象開始?如果你能夠使用'lapply'並將它們放入一個'list'中,那不夠嗎? – A5C1D2H2I1M1N2O1R2T1

回答

2

你真的應該在這裏使用一個列表:

# 
ben <- <list of all your ben's> 
mal <- <list of all your mal's> 

fex <- mapply(rbind, ben, mal) 

# then just index using 
fex[[i]] 

如果你必須有獨立的變量,使用assign

N <- 30 # however many of each `ben` and `mal` you have 
for (i in N) { 
    bi <- paste0(ben, i) 
    mi <- paste0(mal, i) 
    fi <- paste0(fex, i) 

    assign(fi, rbind(get(bi), get(mi))) 
} 

注意收集你的對象到一個列表:

ben <- lapply(do.call(paste0, list("ben", 1:N)), get) 
mal <- lapply(do.call(paste0, list("mal", 1:N)), get) 

# Which can then be indexed by 
ben[[7]] 
mal[[12]] # etc 

但是,您還應該嘗試將它們放在getgo的列表中。