Hala
Hala

Reputation: 41

Importing multiple csv files at the same time want the date data converted into (date and time) format in R

I have 20 files as .csv; all have the same headers as in the picture.

This is how my data looks like

I want to import them once at the same time. I want the timestamp converted from character format to date and time format.

I used this code for importing all the 20 files, which works fine.

path <- "~/Google Drive/Plumeflowlabs test/Data from Plume 17 Nov 2020/"

files <- list.files(path=path, pattern="*.csv")

for(file in files)
{
  perpos <- which(strsplit(file, "")[[1]]==".")
  assign(
    gsub(" ","",substr(file, 1, perpos-1)),
    read.csv(paste(path,file,sep="")))

}

However, it doesn't contain the function to convert the date.

After that, I want to merge all the 20 files into one data frame by the timestamp.

I need help with that too.

Upvotes: 0

Views: 350

Answers (1)

Duck
Duck

Reputation: 39595

Try this approach. As no data was shared I can not test it. Taking into account the sage advice from @GregorThomas it is better to store data in a list like this:

#Code
path <- "~/Google Drive/Plumeflowlabs test/Data from Plume 17 Nov 2020/"
files <- list.files(path=path, pattern="*.csv")
#Function to load and transform date
myfun <- function(x)
{
  df <- read.csv(x,sep="")
  df$timestamp <- as.POSIXct(df$timestamp,format='%d/%m/%Y %H:%M',tz = 'GMT')
  return(df)
}
#Apply
List <- lapply(files,myfun)
#Names
names(List) <- files

The names are assigned in reference to files object. After that you can process them.

Upvotes: 1

Related Questions