用文件夹

时间:2016-06-14 08:45:55

标签: r filenames substitution columnname

我在一个文件夹中有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)
}

但我不知道怎么写当前文件的名称如chin001 部分,谢谢你的回复

1 个答案:

答案 0 :(得分:1)

从文件名中删除.txt部分(有很多方法可以执行此操作),然后用该名称替换第一列名称。

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