Annika
Annika

Reputation: 1

Inserting file names as column headers in a data frame

I am relatively new to R and I and I am not able to find a solution that works for my problem specially.

I have created a list of many csv. files. The name of each file is the date in the form of 'yyyy-mm-dd'. (There is nothing within the file which helps me identify the date on which the file was generated, only the filename has that information.)

I then read in each .csv file in file_list and created data frames using the following code:

for (i in 1:length(file_list)){
  aux<-readLines(paste(folder,file_list[i], sep = "")) %>%
    str_replace_all(" %", "") %>% 
    head(-2)
  aux2<-lapply(aux, function(x){drop_trailing_semicolon(x)}) %>% unlist()

  assign(file_list[i],read.csv(text=paste0(aux2, collapse="\n "), skip=5, header=TRUE, sep=";", dec=",",stringsAsFactors =FALSE, na.strings=c("-", " ")))
}

I then put all data.frames into one list. I will need to compare the data from different days, but I won't be able to identify the date the data was collected. Hence I want to insert the filename as a header of a new column in the respective file. Is their a way to insert the column within the function I use? Or even a completely different solution?

Any help would be greatly appreciated. Thank you in advance, Annika

Upvotes: 0

Views: 201

Answers (1)

RDS
RDS

Reputation: 79

You could use names, in your case names(listOfDataFrames) <- file_list

a = list(1,2,3)
names(a) = c("first", "second", "third")

a$first
[1] 1

Upvotes: 1

Related Questions