我有一个关于在 R 中避免 for() 循环的问题。我查看了有关该主题的所有帖子,但没有任何答案可以回答我的问题。所以在这里,我有两个数据文件,一个包含 60 个城市的纬度和经度文件(参见这个CSV 文件)和一个包含多个变量的二维数组文件(参见这个netCDF 文件)。我有一个小计算,可以将每个纬度经度转换为行列。在行列计算之后,这些数字用于编辑 netCDF 文件中的变量。在下面的 REVISED 代码中,我使用了 for() 循环。有没有办法避免 for() 循环和 if() 条件?
#install.packages("ncdf4", dependencies = T)
library(ncdf4)
episim <- nc_open("England_aggr_GPW4_2000_0000.nc", write = TRUE)
currInhabitable <- t(ncvar_get(episim, episim$var[[4]]))
S <- t(ncvar_get(episim, episim$var[[1]]))
I <- matrix(0, 64, 44, byrow = T)
outbreak <- read.csv("60cities-lat-lon.csv", header = T)
for (ff in 1:dim(outbreak)[1])
{
row <- abs(round((outbreak[ff,2] - 55.25833)/0.08333333))
col <- abs(round((outbreak[ff,3] + 5.416667)/0.1666667))
newInf <- outbreak[ff,4]
#print(paste("Is the current cell inhabitable or not?", currInhabitable[row, col]))
if (currInhabitable[row, col] == 1 & S[row, col] > newInf)
{
S[row,col] <- S[row,col] - newInf
I[row,col] <- I[row,col] + newInf
}
print(c(row, col, S[row,col], I[row,col]))
}
t = 1
print(paste("Epidemic state saved to a netCDF file on day", t))
episimNew <- nc_create(paste("England_aggr_GPW4_2000_000", t, ".nc", collapse="", sep=""), episim$var)
ncvar_put(episimNew, episimNew$var[[1]], t(S))
ncvar_put(episimNew, episimNew$var[[2]], t(I))
nc_close(episimNew)
nc_close(episim)