2016-06-14 10 views
0

私はchin01.txt、chin02.txtのように見える1つのフォルダーに200ファイルがあります。各.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) 
} 

が、私は、このようなchin001一部としてcurrentFileの名前を書く方法がわからない、任意の返信

答えて

1

をありがとうございましたから.txtの一部を削除しますfilename(これにはたくさんの方法があります)、最初の列名をその名前に置き換えます。

currentFile <- sub(".txt", "", file) # file could be e.g. filename.txt 
names(file)[1] <- currentFile 
関連する問題