2013-02-03 36 views
4

這是一個雙桶裝R問題。我有一個數據集文件夾(以.csv格式),他們需要在分析之前進行修改。每個數據集是一個1X10矩陣,如:重新排列R中的多個矩陣的形狀

1 2 3 4 5 6 7 8 9 10 

,需要把它變成爲以下5x5矩陣對角線上的插入1S:

1 
1 1 
2 3 1 
4 5 6 1 
7 8 9 10 1 

如何能在一個多個文件完成這個轉型夾?

+0

什麼文件類型? – N8TRO

+0

他們是csv文件 – bencrosier

回答

7

試試這個:

dir.in <- "aaa" # replace with your own input dir 
dir.out <- "bbb" # replace with your own output dir 

files.in <- list.files(dir.in, full.names = TRUE) 
files.out <- file.path(dir.out, basename(files.in)) 

data.in <- lapply(files.in, scan, sep = ",") 

mat.out <- lapply(data.in, function(x){ M <- diag(1, 5) 
             M[upper.tri(M)] <- x 
             t(M) }) 

mapply(write.csv, mat.out, files.out, col.names = FALSE, row.names = FALSE) 
+0

我試過了,並得到以下錯誤:> data.in < - lapply(files.in,scan,sep =「,」) 文件(文件,「r」)中的錯誤:無法打開連接 此外:警告消息: 在文件(文件,「r」)中:無法打開文件'sn1.csv':沒有這樣的文件或目錄 – bencrosier

+0

檢查你的工作目錄'getwd()' – tcash21

+0

嘗試'full.names = TRUE'。編輯。 – flodel