1

次のようなパターンを持つ入力ファイルがあります: - 最初の 2 行には、モデルと月と年のパラメーターが含まれています: これらの 2 行から月と年を取得するだけで済みます - 次のブロックには実際のデータが含まれています: 172 行および256列データはN回続きます

実際のデータへのリンク

もう 1 つのファイルは ArcGIS ASCII グリッドで、最初の 6 行は ArcGIS パラメーターで、172 行 x 256 列のブロック (領域内では 1、その他では -9999 に等しい) です。

ArcGIS ASCII グリッドへのリンク

私がやりたいことは、データを読み取り、マスク グリッドに基づいて各タイム ステップの平均値を計算することです。現時点で私が考えることができる唯一の方法は、3つのネストされたループを使用することです

for (i in 1:N) {
   for (j in 1:172) {
      for (k in 1:252) {
           Read the data
           Do calculation
           Write the result out
      }
   }
{

このような複雑な FOR ループの使用を避ける良い方法はありますか? どんな提案でも大歓迎です!

編集: agstudy の提案やその他の情報源に基づいて、データを 1 行ずつ読み取り、strsplit を使用して値を取得します。私の最終的なコードは次のとおりです

########################## Read the grid first ########################
con <- file(gisGrid) 
open(con);

# Read the first 6 lines
gisData <- readLines(textConnection(
'ncols         256
nrows         172
xllcorner     730000
yllcorner     227000
cellsize      1320
NODATA_value  -9999'),n=6)

# Extract value
gisPara <- matrix(unlist(strsplit(gisData,' +')), ncol=2, byrow=TRUE)
summary(gisPara)

# Read the mask grid:
gridValue <- read.table(file = gisGrid, header = FALSE, skip=6)
gridValueVec <- as.vector(as.matrix(gridValue))

close(con)

######################### Read the data file #########################
con <- file(dataFile) 
open(con);

# Define number of timesteps, nRow, nCol
nTime <- 3
nRow <- 172
nCol <- 256

# Read the whole file in
data.lines <- scan(con, what=character(), sep='\n')
data <- NULL
# Create 3D object to store data for each timestep
data$timestep <- list( rep( matrix(nrow=nRow, ncol=nCol), nTime ) )
data$month <- list( rep( nTime ) )
data$year <- list( rep( nTime ) )
data$multiply <- list( rep( nTime ) )

# Loop over all timestep
for (i in 1:nTime) {
  # Read the first 2 lines
  data.lines <- data.lines[-1] # remove line from the dataset

  data.line2 <- strsplit(data.lines[1],' ')
  data$month[[i]] <- data.line2[[1]][24]
  data$year[[i]] <- as.numeric(data.line2[[1]][25])
  data.lines <- data.lines[-1]

  dataRead <- matrix(nrow=nRow, ncol=nCol)
  for(j in 1:nRow) 
  {
    dataRead[j,] <- as.numeric(strsplit(data.lines[1],' ')[[1]])
    data.lines <- data.lines[-1]
  }         

  # Multiply data with the mask grid
  dataReadVector <- as.vector(dataRead)
  gridMultiplication <- ifelse(gridValueVec==-9999, NA,
                               dataReadVector * gridValueVec )

  data$multiply[[i]] <- mean(gridMultiplication, na.rm=TRUE)
  data$timestep[[i]] <- dataRead
}

close(con)
4

1 に答える 1