2015-09-11 54 views
0

我有一個文件在dir1這樣命名:File_01_02_2013.img
我有一個名爲像這樣的另一個文件夾dir2其他文件:如何將值與文件名匹配?

File_01_02_2013_00.img 
File_01_02_2013_01.img 

所以我有一個文件a matrixdir1,但24個文件中dir2
我需要的是:

00 …>>>> File_01_02_2013_00.img >>>> 4 >>>> put in the new matrix `out_01_02_2013_.img` 

要閱讀DIR1文件:

con <- file("C:\\dir1\\ File_01_02_2013.img", "rb") 
pva<- readBin(con, numeric(), size=4, n=1000*500) 
dat <- matrix((data=pva), ncol=500, nrow=1000) 

讀取文件DIR2:

這24個文件具有相同的dimFile_01_02_2013.img和能通過上面的相同的行閱讀。

+0

沒有必要匹配文件名。 'dir2'是一個有序的字符矢量,包含從「... 00.img」到「... 23.img」的文件名。所以如果你閱讀'03',你可以將它轉換爲數字並讀取第四個文件:'readBin(dir2 [[as.numeric(「03」)+ 1]],...)''。 – sgibb

回答

1

sgibb是正確的,如果dir2中的文件名包含00到23的所有值,那麼要訪問說...04.img的文件,您希望在您的dir2列表中打開第五個文件。

所以假設你在你的DAT矩陣獲得的第一個值

val <- dat[1,1] 

val等於4,那麼你就可以訪問使用readBin(dir2[[val + 1]]...(如果dat值是數字的第五個文件。如果他們不是,你必須將它轉換爲數字,如在sgibb的評論中)。

現在當你的意思是「提取相應的值」,你的意思是使用你用來獲得val以上的指數?那麼你想加載dir2文件,然後從中獲得價值[1,1]?然後取這個值並將其放入最終矩陣中的[1,1]

編輯

澄清後,這裏有一個(不是很優雅)的事情你可以做:

nrows <- 1000 
ncols <- 500 
outmat <- matrix(,nrows,ncols) 
for (nr in 1:nrows){ 
for(nc in 1:ncols{ 
    val <- dat[nr,nc] 
    dir2file <- readBin(dir2[[val + 1]], numeric(), size=4, n=1000*500) 
    dir2val <- dir2file[nr,nc] 
    outmat[nr,nc] <- dir2val 
} 
} 

編輯#2

這裏的通過你的整個數據集,試圖循環。由於您沒有提供任何示例數據,因此我無法測試此代碼,所以我無法保證它在您不必調試的情況下工作。但也許你是幸運的;-)

dir1 <- list.files("C:\\dir1", "*.img", full.names = TRUE) 
dir2 <- list.files("C:\\dir2", "*.img", full.names = TRUE) 

# get a list of strings of just the file names 
dir1str <- list.files("C:\\dir1", "*.img", full.names = FALSE) 


nrows <- 1000 
ncols <- 500 

for (fileInd in length(dir1)){ 
    # read in file 1 of dir1 (copied from your code) 
    pva<- readBin(dir1[[fileInd]], numeric(), size=4, n=1000*500) 
    dat <- matrix((data=pva), ncol=500, nrow=1000) 

    # retrieve the file name of dir1 
    dir1strfile <- dir1str[[fileInd]] 
    # split the string at the underscores (_) 
    file.attr <- unlist(strsplit(dir1strfile,"_")) 
    # Paste the strings back together to get File_date 
    fdate <- paste0('File_',file.attr[2],'_',file.attr[3]) 

    # Get indeces of files in dir2 that match the date 
    dir2date <- grep(fdate,dir2) 
    dir2lst <- dir2[dir2date] 

    # pre-allocate output matrix 
    outmat <- matrix(NA,nrows,ncols) 

    # now loop through the dir1 file, and save the outmat as a csv 
    for (nr in 1:nrows){ 
    for(nc in 1:ncols){ 
     val <- dat[nr,nc] 
     dir2file <- readBin(dir2lst[[val + 1]], numeric(), size=4, n=1000*500) 
     outmat[nr,nc] <- dir2file[nr,nc] 
    } 
    } 
    # you probably have to turn the '/' into a '\' below 
    outname <- paste0(dir2, '/' ,fdate,'_output.csv') 
    write.csv(outmat,outname) 
    } 

我也很感激,如果有人發佈了更優雅的解決方案!

+1

當然。 'dir2'文件是否也以相同的方式格式化,所以:'File_02_02_2013_00.img - > File_02_02_2013_23.img'? – MSJ

+1

試試我的編輯#2,也許它有效! – MSJ

+0

你對我們如何能更快做到有什麼想法嗎? – temor

相關問題