[英]Optimizing for loop in R
我一直在做很多研究,我想在R中嵌套循環時會丟失一些東西。我有兩個數據框-一個包含觀察值和位置,我想在其中寫輸出,另一個包含變量名我正在遍歷。 目前,該循環有效,但是要遍歷200行需要14個多小時,這似乎有點多余。 當然,我希望每行執行12個單獨的排列(100次),盡管我理想情況下希望執行> 1000+個排列。 有沒有更有效的方法來執行此for循環? 當我進行單個觀察時,只需很少的時間(不到2秒)即可完成,這使我感到困惑的是,應該有一種更好的方法來完成此任務。 您可以在優化此代碼方面提供的任何幫助將不勝感激! 謝謝!
附加了主要數據集(fbfm.xlsx),稱為fm.std https://www.dropbox.com/s/vmd8d05yxds93j6/fbfm.xlsx?dl=0
library(rothermel)
u.val<-c(5,10,15,25,35,45,55,65,75,85,95,100)
unames <- data.frame(u=u.val,ros.nam=paste("u",u.val,"_ROS",sep=""), stringsAsFactors = FALSE)
ros.out<-data.frame(fm.std)
for (i in 1:dim(unames)[1]){
ros.out[,unames[i,'ros.nam']]<-999
}
ros.out <- as.vector(ros.out)
fm.std <- as.vector(fm.std)
for (i in 1:dim(ros.out)[1]){
ros.out[i,1:32]
for (u in 1:dim(unames)[1]){
ros.out[i,unames[u,'ros.nam']]<-mean(rosunc(modeltype=fm.std[i,'Fuel_Model_Type'], #Dyanmic or static model
w=fm.std[i,4:8], # fuel loads (1, 10, 100, herb, and shrub)
s=fm.std[i,9:13], # SAV measurements
delta=fm.std[i,14], #fuel bed depth
mx.dead=fm.std[i,15], # dead fuel mositure of extinction
h=fm.std[i,16:20], # heat content for fuel classes
m=fm.std[i,c(25,24,23,26,30)], #percent moisture of fuel classes
u = unames[u,'u'],
slope=0,
sdm=0.3,
nsim=100) ) #wind and slope of 0 }}
考慮傳入兩個向量u.val
和1:nrow(fm.std)
的更具向量化的sapply()
方法。 這將建立一個200行,12列的矩陣,您可以將其轉換為數據cbind
,然后cbind
為原始數據cbind
。
ucols <- sapply(u.val,
function(x, y){
mean(rosunc(modeltype=fm.std[y,'Fuel_Model_Type'], # Dyanmic or static model
w=fm.std[y,4:8], # fuel loads (1, 10, 100, herb, and shrub)
s=fm.std[y,9:13], # SAV measurements
delta=fm.std[y,14], # fuel bed depth
mx.dead=fm.std[y,15], # dead fuel mositure of extinction
h=fm.std[y,16:20], # heat content for fuel classes
m=fm.std[y,c(25,24,23,26,30)], # percent moisture of fuel classes
u=x,
slope=0,
sdm=0.3,
nsim=100))
}, 1:nrow(fm.std))
# CONVERT MATRIX TO DATA FRAME
ucols <- data.frame(ucols)
# RENAME COLUMNS
names(test) <- paste("u",u.val,"_ROS",sep="")
# BIND COLUMNS TO ORIGINAL DATA FRAME
ros.out <- cbind(fm.std, ucols)
或者,考慮將outer()
與轉置t()
以實現200行12 col矩陣。
ucols <- t(outer(u.val, 1:nrow(fm.std),
function(x, y){
mean(rosunc(...))
}
))
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.