2014-10-05 41 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

相关问题