简体   繁体   中英

Merging multiple text files into one using R

I am trying to merge multiple text files into a csv and have done it successfully using the following code. I have one additional requirement, I need to add the name of the file in a separate column indicating where the data came from. Please suggest.

rm

(list=ls())
setwd("D:/Cersai Rejection Reasons/IT_Oct18-Jun19")
file_list <- list.files()
df <- data.frame(file_list)

library(plyr)   
library(dplyr)

files <- dir("D:/Cersai Rejection Reasons/IT_Oct18-Jun19", 
             full.names = TRUE)
df <- lapply(files, function(x) 
  read.table(x, sep = '\t', header = FALSE)) %>% 
  plyr::ldply() 
write.csv(df, file="D:/consolidatetext.csv")
library(dplyr)
df <- lapply(files, function(x) {
  df <- read.table(x, sep = '\t', header = FALSE, stringsAsFactors = FALSE)
  df$source <- x
  return(df)
}) %>%
  bind_rows()

write.csv(df, file="D:/consolidatetext.csv")

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