我有一個關於在R中避免for()循環的問題。我已經查看了關於該主題的所有帖子,沒有任何回答我的問題。所以在這裏,我有兩個數據文件,一個文件包含60個城市的經緯度(參見CSV file)和一個包含多個變量的二維數組文件(請參閱此netCDF file)。我有一個小的計算,將每個緯度轉換爲一個行。在行計算之後,這些數字用於編輯netCDF文件中的變量。在下面的REVISED代碼中,我使用了for()循環。有沒有辦法避免for()循環和if()條件?避免for()循環,如果在R
#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)
看看'sapply'鏈接這裏:https://www.datacamp.com/community/tutorials/r-tutorial-apply-family – Wen