0

I have 200 files in one folder looks like chin01.txt, chin02.txt ect. each read.table of each .txt file produce a n rows by 2 column data frame with column and row names.

now I want to change the first column name of each data frame to corresponding file name, such as chi001, what I should do? below are my first lines of codes:

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) } 

but I don't know how to write name of currentFile such as chin001 part, thank you for any reply

1 Answer 1

1

Remove the .txt part from the filename (there are plenty of ways of doing this) then replace the first column name with that name.

currentFile <- sub(".txt", "", file) # file could be e.g. filename.txt names(file)[1] <- currentFile 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.