【发布时间】:2015-10-04 23:54:42
【问题描述】:
有没有什么方法可以通过应用函数来加速下面的 R 代码?我还不能完全理解 apply 函数的实现,但我知道它们可能有助于减少 for 循环的计算时间。
这是代码,感谢您的输入!
for(i in 1:(365 + leap)){
## Filename
IMS.file = paste('crb_',km,'km_v00_',year,
sprintf("%03d", i),'.asc.csv',sep='')
## The next step is to check that file exists
if(file.exists(paste(IMS.folder,'/',IMS.file,sep=''))){
## Reads in file
dat = read.table(paste(IMS.folder,'/',IMS.file,sep=''),
sep=',')
## This removes all the values outside of the basin
point.in.polygon(dat[,4],dat[,3],basin.coord[,1],basin.coord[,2])
xy = as.logical(point.in.polygon(dat[,4],dat[,3],basin.coord[,1],basin.coord[,2]))
## Keeps points of interest, eliminates first 2 columns and reverses lat & lon
dat = dat[xy,3:5]
## Changes 4 to snow (1) and all others to 0
dat[,3] <- ifelse(dat[,3] == 4,1,0)
## Creates a new file (may need to be updated for new computers)
newfile = paste('C:/Users/Ben/Documents/Columbia Project/',
'ColumbiaRiverBasin_Report/IMS',km,'SubBasins/',subbasin,
'/',year,'/',year,sprintf("%3d", i),'.csv',sep='')
## Adds the file header to the spreadsheet
write.table(file.head,file=newfile,quote=FALSE,row.names=FALSE,
col.names=FALSE)
## Appends file with the trimmed data
write.table(dat,file=newfile,append=TRUE,
quote=FALSE,row.names=FALSE,col.names=FALSE,sep=',')
}
else{
## Outputs missing day (1-366 )
print(paste('Missing Day Number: ', i),quote=FALSE)
}
}
【问题讨论】:
-
可能不会:(1) 应用函数通常最多会导致非常轻微/微妙的速度提升(搜索并阅读 Patrick Burns 的 R Inferno); (2)如果可能的话,通常需要矢量化; (3) 如果您必须单独处理日常文件,您可能会搞砸。唯一的例外是您可以使用
parallel包中的apply()的并行 版本... -
PS 我不知道你的瓶颈在哪里(很可能是
points.in.polygon或文件 I/O),但是 . ...在第二次运行并存储结果之前,您是否有理由无用地运行point.in.polygon(dat[,4],dat[,3],basin.coord[,1],basin.coord[,2])一次? -
本-谢谢;我什至没有注意到这一点,它确实加快了速度。
标签: r