Skip to content

How to insert filename as column in a file

7 messages · jim holtman, MacQueen, Don, Shivam +1 more

#
This might do it for you:


for (i in fileNames){
    input <- read.table(i, .....)
   # you might want to use regular expressions to extract just the date.
    input$fileName <- i
    write.table(i, ....)
}
On Mon, Apr 23, 2012 at 12:29 PM, Shivam <shivamsingh at gmail.com> wrote:

  
    
#
This little example might help.
a b
1   1 a
2   2 a
3   3 a
4   4 a
5   5 a
6   6 a
7   7 a
8   8 a
9   9 a
10 10 a
a b     date
1   1 a 20120423
2   2 a 20120423
3   3 a 20120423
4   4 a 20120423
5   5 a 20120423
6   6 a 20120423
7   7 a 20120423
8   8 a 20120423
9   9 a 20120423
10 10 a 20120423


In other words, immediately after reading the data into a data frame, add
a date column as in the example. You'll have to extract the date from the
filename, of course.

-Don
#
Programatically dealing with large numbers of separately-named objects leads to syntactically complicated code that is hard to read and maintain. 

Load the data frames into a list so you can access them by numeric or named index, and then getting at the loaded data will be much easier.

fnames = list.files(path = getwd())
# preallocating the list for efficiency (execution speed)
dtalist <- vector( "list", length(fnames) )
for (i in seq_len(length(fnames))){
  dtalist[[i]] <- read.csv.sql(fnames[i], sql = "select * from file where V3 == 'XXX' and V5=='YYY'",header = FALSE, sep= '|', eol ="\n"))
 dtalist[[i]]$date <-  substr(fnames[i],1,8)) 
}
names(dtalist) <- fnames
# now you can optionally refer to dtalist$file20120424.csv or dtalist[["file20120424"]] if you wish.
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
--------------------------------------------------------------------------- 
Sent from my phone. Please excuse my brevity.
Shivam <shivamsingh at gmail.com> wrote:

            
1 day later