简体   繁体   中英

Read Multiple txt files in an order and combine them into one dataframe but label the origin of each row in the new generated dataframe in r

I have 6 txt files and I want to combine them into 1 dataframe. I know how to read them simultaneously and combine them in default way. I learned to do this in this website:

txt_files_ls = list.files(path=mypath, pattern="*.txt") 
txt_files_df <- lapply(txt_files_ls, function(x) {read.table(file = x, header = T, sep ="\t")})
# Combine them
combined_df <- do.call("rbind", lapply(txt_files_df, as.data.frame))

Now I want to do is set the read.table to read the txt files in a sequential manner as i defined, So that after combining them, I will be able to labeled the rows with the name of their original txt file name. Thank you

You can try this:

txt_files_ls = list.files(path=mypath, pattern="*.txt") 
#The function for reading
read.data <- function(x)
{
  y <- read.table(file = x, header = T, sep ="\t")
  y$var <- x
  return(y)
}
#Read data
txt_files_df <- lapply(txt_files_ls,read.data)
# Combine them
combined_df <- do.call("rbind", lapply(txt_files_df, as.data.frame))

Where var contains the name of each file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM