2014-10-05 23 views
2

我有文件名爲P1.txt P2.txt ........P100.txt。 我想要做的應用在其中的每個文件的以下功能:如何在R中的每個文件上應用此函數?

temp <- P1.txt 
colnames(temp) <- c("a","b") 
temp <- aggregate(count~a+b,transform(temp,a=pmin(a,b), b=pmax(a,b), count=1),sum) 
colnames(temp) <- c("V1","V2","V3") 
P1.txt <- temp 

如何爲每個文件自動執行此? 我能拿出`paste0(「P」,我,「.txt」),我將從1到100不等,但我不知道如何再次分配它?謝謝!

編輯:單個文件是最初包含兩列和1000行的數據框。 樣品:(P1.txt)

1 2 
3 4 
4 2 
4 5 
.... 
+0

請提供有關文件結構的信息。 – 2014-10-05 08:05:21

回答

1

只有部分答案,因爲你沒有給我們的文件的結構...

如果你想在這些文件的讀取,並把它們寫出來,那麼你將需要明確地做到這一點,例如read.csv()write.csv()。然後,你可以:

for(i in 1:100) { 
    fnam <- paste('P', i, '.txt', sep='') 
    temp <- read.csv(fnam, header=FALSE) 
    # manipulate the contents... 
    colnames(temp) <- c("a", "b") 
    temp <- aggregate(count ~ a + b, 
        transform(temp, a = pmin(a, b), b = pmax(a, b), count = 1), 
        sum) 
    colnames(temp) <- c("V1", "V2", "V3") 
    # save the results 
    write.csv(temp, fnam, row.names=FALSE, col.names=FALSE) 
} 

但是,要小心,否則可能過度寫你P1..P100.txt文件驗證其正確性之前使用這個的!

+0

我已經添加了文件的結構。 – 2014-10-05 08:13:00

+0

這不會覆蓋文件。這是我想要做的,但沒有發生。我用'write.table(temp,fnam)' – 2014-10-05 08:16:28

1

這是一種方法。

# generate list of files 
files <- list.files(pattern = "^P\\d+\\.txt$") 

for (file in files) { 
    temp <- read.table(file) 
    colnames(temp) <- c("a", "b") 
    temp <- aggregate(count ~ a + b, 
        transform(temp, a = pmin(a, b), b = pmax(a, b), count = 1), 
        sum) 
    colnames(temp) <- c("V1", "V2", "V3") 
    write.table(temp, file, row.names = FALSE) 
} 
+0

這不會覆蓋名爲'P1.txt ... P100.txt'的文件。 – 2014-10-05 08:35:14

+0

它仍然不覆蓋文件。這就是問題。 – 2014-10-05 11:12:26

+0

@chanchong您是否有權覆蓋文件? – 2014-10-05 12:38:14

相關問題