Rのfor()ループを避けることについて質問があります。このトピックに関するすべての投稿を見て、何も答えません。ここでは、60都市の緯度と経度を持つ2つのデータファイル(CSV file参照)と、複数の変数を持つ1つの2D配列ファイル(netCDF fileを参照)があります。私はそれぞれの緯度経度を行colに変換する小さな計算を持っています。 row-col計算後、これらの数値は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)
を見てここ:https://www.datacamp.com/community/tutorials/r-tutorial-apply-family – Wen