为nc代码循环并按行排列数据

问题描述 投票:0回答:1

我有以下nc文件的代码。此代码为我的工作目录中存在的所有netcdf文件生成单独的csv文件。它按行排列数据。它会跳过经度和纬度甚至名称或序列号,并将其替换为V1,V2等。

任何人都可以帮我解释为什么它不包括纬度/经度甚至序列号以及为什么它显示为V1,V2,V3的顶行?

如何在1个单独的csv文件中获取所有nc文件的数据。我的意思是单个csv输出文件应包含用于标题的顶部(第1行)csv(站名或序列号或者甚至是V1,V2 ......)和第1行用于第1个nc文件数据,第3行用于第2个nc文件数据,第3行nc文件数据的第4行,依此类推。

我附加了输入csv的图片,其中包含坐标和1个单个csv输出,用于1个nc文件。

library(ncdf4)
library(raster)

setwd("F:\\research\\1_Rainfall\\CDC\\test")
files <- list.files(pattern="*.nc")
print(files)
ncname <- files[1:3]
ncfname <- paste(ncname, sep="")

library(raster)

dname <- "precip"  # note: variable precipitation or temperature

for(i in 1:3){
  ncin1 <- brick(ncfname[i])
  s = read.csv("F:\\research\\1_Rainfall\\CDC\\test\\Remaining_Points.csv", 
               stringsAsFactors = FALSE)
  coordinates(s)= ~lon + lat 
  e <- extract(ncin1, s)

  ts1 <- round((e),1)
  df <- as.data.frame(t(ts1))

  write.csv(df, 
            file = paste0("F:\\research\\1_Rainfall\\CDC\\test\\precip", i, ".csv"), 
            append=FALSE, sep= ",", row.names = TRUE, col.names=TRUE)
}
r loops csv netcdf netcdf4
1个回答
1
投票

当您提出问题时,请提供一个简单的可重复示例。并试着将你的问题分解成几部分。您有两个问题(1)如何存储您逐行提取的数据,以及(2)如何附加到文件。我会回答#1,因为你可能不需要#2。

library(raster)
files <- rep(system.file("external/rlogo.grd", package="raster"), 3)
xy <- matrix(c(48, 48, 48, 53, 50, 46, 54, 70, 84, 85, 74, 84, 95, 85, 
   66, 42, 26, 4, 19, 17, 7, 14, 26, 29, 39, 45, 51, 56, 46, 38, 31, 
   22, 34, 60, 70, 73, 63, 46, 43, 28), ncol=2)
stations <- letters[1:nrow(xy)]

outf <- "precip.csv"
d <- data.frame(t(xy))
colnames(d) <- stations
d <- cbind(file="", var=c("x", "y"), d)

for(i in 1:length(files)){
    nc <- brick(files[i])
    e <- t(extract(nc, xy))
    colnames(e) <- stations
    v <- data.frame(file=basename(files[i]), var=names(nc), e)
    d <- rbind(d, v)
}
rownames(d) <- NULL
head(d)

现在一步将结果写入csv

write.csv(d, outf)

如果必须按块编写csv块,可能会执行以下操作:

    d <- data.frame(t(xy))
colnames(d) <- stations
d <- cbind(file="", var=c("x", "y"), d)
outf <- "precip.csv"
if (file.exists(outf)) file.remove(outf)
write.csv(d, outf, row.names=FALSE) 
for(i in 1:length(files)){
    nc <- brick(files[i])
    e <- t(extract(nc, xy))
    colnames(e) <- stations
    v <- data.frame(file=basename(files[i]), var=names(nc), e)
    write.table(v, outf, append=TRUE, row.names=FALSE, col.names=FALSE, sep=",")
}

并检查:

read.csv(outf)   

你的代码清理了一下,看起来像这样:

库(ncdf4)库(栅格)

files <- list.files(pattern="*.nc")
library(raster)
s <- read.csv("Remaining_Points.csv", stringsAsFactors = FALSE)
xy <- s[, c("lon", "lat")]
stations <- s$stationname

for(i in 1:length(files)){
  nc <- brick(files[i])
  e <- t(round(extract(nc, xy), 1))

  # etc
}

现在我认为您应该考虑将值添加为列,因为这样更容易。 (然后在需要时根据需要重新塑造)

© www.soinside.com 2019 - 2024. All rights reserved.