我有名为P1.txt P2.txt ........P100.txt
的文件。
我想对每个文件应用以下函数:
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",i,".txt"),其中 i 的范围从 1 到 100,但我不知道如何再次分配它?谢谢!
编辑:各个文件是最初包含两列和 1000 行的数据帧。 示例:(P1.txt)
1 2
3 4
4 2
4 5
....
最佳答案
这是一种方法。
# 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)
}
关于r - 如何在 R 中的每个文件上应用此函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26200682/