I am working with 600 csv files. I want to import them all into a vector. I can write code for each, one at a time like this (using just 4 of the files as an example):
## Import for CSV files
csv1 <- read.csv("csvFiles/csv1.csv", stringsAsFactors=FALSE)
csv1.df <- as.data.frame(csv1)
names(csv1.df) <- c("text")
csv1.vc <- paste(csv1.df$text, collapse=" ")
csv2 <- read.csv("csvFiles/csv2.csv", stringsAsFactors=FALSE)
csv2.df <- as.data.frame(csv2)
names(csv2.df) <- c("text")
csv2.vc <- paste(csv2.df$text, collapse=" ")
csv3 <- read.csv("csvFiles/csv3.csv", stringsAsFactors=FALSE)
csv3.df <- as.data.frame(csv3)
names(csv3.df) <- c("text")
csv3.vc <- paste(csv3.df$text, collapse=" ")
csv4 <- read.csv("csvFiles/csv4.csv", stringsAsFactors=FALSE)
csv4.df <- as.data.frame(csv4)
names(csv4.df) <- c("text")
csv4.vc <- paste(csv4.df$text, collapse=" ")
## Combine all vectors into a single data frame
final.vc <- c(csv1.vc, csv2.vc, csv3.vc, csv4.vc)
Encoding(final.vc) <- "UTF-8"
I know there must be a way for R to import all the files in my directory and combine them into the vector how I want, without having to write 4 lines of code for each of the 600 csv files. I think it's something like this, but I'm just not getting it right. I'm quite new to coding, R, and R-script
## Import for CSV files
files <- list.files(path = "csvFiles", pattern = ".csv$", full.names = TRUE)
csv2vector <- function(company){
csvfile <- read.csv(file="filename", stringsAsFactors=FALSE)
csfvile.df <- as.data.frame(csvfile)
names(csvfile.df) <- c("text")
csvfile.vc <- paste(csvfile.df$text, collapse=" ") # Creates a single vector
## Combine all vectors into a single data frame
companyvec <- c(company)
names(companyvec) <- c("company")
final.vc <- c(companyvec)
}
lapply(files, csv2vector)
Any help and advice is appreciated. thanks.