私はRを扱うのはかなり新しいですが、これを成し遂げようとしています。ディレクトリに数十の ENVI スペクトル データセットが保存されています。各データセットは 2 つのファイルに分かれています。それらはすべて同じ命名規則を持っています。
- ID_YYYYMMDD_350-200nm.asr
- ID_YYYYMMDD_350-200nm.hdr
タスクは、データセットを読み取り、2 つの列 (ファイル名からの ID と日付) を追加し、結果を *.csv ファイルに保存することです。これを単一のファイル(ハードコード)で機能させるようにしました。
library(caTools)
setwd("D:/some/path/software_scripts")
### filename without extension
name <- "011a_20100509_350-2500nm"
### split filename in area-id and date
flaeche<-substr(name, 0, 4)
date <- as.Date((substr(name,6,13)),"%Y%m%d")
### get values from ENVI-file in a matrix
spectrum <- read.ENVI(paste(name,".esl", sep = ""), headerfile=paste(name,".hdr", sep=""))
### add columns
spectrum <- cbind(Flaeche=flaeche,Datum=as.character(date),spectrum)
### CSV-Dataset with all values
write.csv(spectrum, file = name,".csv", sep=",")
利用可能なすべてのファイルを 1 つの *.csv ファイルに結合したいと考えています。list.files を使用する必要があることはわかっていますが、read.ENVI 関数を実装して結果の行列を継続的に CSV に追加する方法がわかりません。
アップデート:
library(caTools)
setwd("D:/some/path/mean")
files <- list.files() # change or leave totally empty if setwd() put you in the right spot
all_names <- sub("^([^.]*).*", "\\1", files) # strip off extensions
name <- unique(all_names) # get rid of duplicates from .esl and .hdr
# wrap your existing code in a function
mungeENVI <- function(name) {
# split filename in area-id and date
flaeche<-substr(name, 0, 4)
date <- as.Date((substr(name,6,13)),"%Y%m%d")
# get values from ENVI-file in a matrix
spectrum <- read.ENVI(paste(name,".esl", sep = ""), headerfile=paste(name,".hdr", sep=""))
# add columns
spectrum <- cbind(Flaeche=flaeche,Datum=as.character(date),spectrum)
return(spectrum)
}
# use lapply to 'loop' over each name
list_of_ENVIs <- lapply(name, mungeENVI) # returns a list
# use do.call(rbind, x) to turn it into a big data.frame
final_df <- do.call(rbind, list_of_ENVIs)
# now write output
write.csv(final_df, "all_results.csv")
ここでサンプル データセットを見つけることができます:サンプル データセット