I have several txt files. Each file has the columns of data separated by a comma. And each has its own individual file name.
So far I have combined these files into one big data frame, using the following code:
files = list.files()
data2=lapply(files, read.table, header=FALSE, sep=",")
data_rbind <- do.call("rbind", data2)
colnames(data_rbind)[c(1,2,3)]<-c("name", "sex", "amount")
This returns:
name sex amount
Anna F 24567
Emma F 23210
Isabelle F 31212
Amanda F 22631
I would like to add a 4th column which specifies next to each line of data, the name of the file that the data was originally sourced from.
So, for example, if the first file 'example1.txt' contained the following:
Anna, F, 24567
Emma, F, 23210
Isabelle, F, 31212
And the second file 'example2.txt' contained the following:
Amanda, F, 22631
Sara, F, 41355
Katie, F, 2387
I would like to get the following:
Name Sex Amount Year
Anna F 24567 example1.txt
Emma F 23210 example1.txt
Amanda F 22631 example2.txt
Sara F 41355 example2.txt
Katie F 2387 example2.txt
Is this possible?