2016-06-14 101 views
0

我在一个文件夹中有200个文件,看起来像chin01.txt,chin02.txt等。每个.txt文件的每个read.table产生具有列名和行名的n行乘2列数据帧。替换列名与文件夹中相应文件的文件名

现在我想把每个数据帧的第一个列名改成相应的文件名,比如chi001,我该怎么办?下面是我的代码的第一行:

files_all <- list.files(path="D:\R\C_test", pattern="*.txt", full.names=T, recursive=FALSE) 

for (currentFile in files_all){ 
    file <- read.table(currentFile, header=F) 
    columnames(file) <- c(**name of currentFile such as chin001**,"depth") 
    write.table(file, file=sub(pattern=".txt$", replacement="_new.txt", x=currentFile),sep="\t", quote=F, row.names=T, col.names=T) 
} 

,但我不知道怎么写currentFile的名称,如chin001一部分,感谢您的任何答复

回答

1

从取出的.txt部分文件名(有很多方法可以做到这一点),然后用该名称替换第一个列名。

currentFile <- sub(".txt", "", file) # file could be e.g. filename.txt 
names(file)[1] <- currentFile