2016-06-14 36 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 
相關問題