[R] "Read.csv" in R with dynamic file (1st) argument

Don MacQueen macq at llnl.gov
Fri Sep 11 04:58:26 CEST 2009


Alternatives to sprintf() include formatC() or 
prettyNum(), which would have to be used in 
combination with paste().

In Carl's solution, the file.path() function 
should be considered, since it automatically uses 
the correct path separators for the OS. 
Furthermore,  eval() is not necessary.

So, for example,

>  x <- formatC(scan(),width=4,flag='0')
1: 23
2:
Read 1 item
>  x
[1] "0023"

root.dir <- 'D:\R\Data'

read.csv( 
file.path(root.dir,x,paste(x,'.csv',sep='')))  ## 
those are all single quotes

This isn't necessarily better than the sprintf() 
version, just different, and shows some 
additional useful functions(). This way of using 
formatC() requires that the user input only 
numbers:

>  x <- formatC(scan(),width=4,flag='0')
1: jk
1:
Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings,  :
   scan() expected 'a real', got 'jk'

I don't know what sprintf() would do with such input.

-Don

At 7:01 PM -0400 9/10/09, Carl Witthoft wrote:
>That will not work (or at least doesn't work for me.
>
>This does work:
>
>fnam<-'thefilename.csv'  #or build the name however you like
>fpath <- 'macintoshhd/users/me/myfolder/  # or whatever you need
>
>read.csv(eval(paste(fpath,fnam,sep=""))  #worked for me
>
>
>Carl
>
>
>
>-----------
>
>Try this:
>
>read.csv(sprintf("D://R//Data//%04d//%04d.csv", x, x), header = TRUE)
>
>On Wed, Sep 9, 2009 at 9:32 PM, Steven Kang <stochastickang at gmail.com>wrote:
>
>>  Dear R users,
>>
>>
>>  I have numerous data sets (csv files) saved in the folder which has the
>>  same
>>  name as individual data.
>>  (i.e data x1 saved in x1 folder, data x2 in x2 folder etc)
>>
>>  I would like to read in the desired data set name using 'scan' function and
>>  assign this inputted value to an object so that it can be used in the
>>  'read.csv' function.
>>
>>  For example,
>>
>>  x <- scan()
>>  1: 0708
>>  2:
>>  Read 1 item
>>
>>  dat <- read.csv("D://R//Data//x//x.csv", head=TRUE, sep = ",")
>>  Error in file(file, "r") : cannot open the connection
>>  In addition: Warning message:
>>  In file(file, "r") :
>>   cannot open file ('D://R//Data//x//x.csv': No such file or directory
>>
>
>
>--
>Henrique Dallazuanna
>Curitiba-Paraná-Brasil
>25° 25' 40" S 49° 16' 22" O
>
>______________________________________________
>R-help at r-project.org mailing list
>https://*stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide http://*www.*R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.


-- 
---------------------------------
Don MacQueen
Lawrence Livermore National Laboratory
Livermore, CA, USA
925-423-1062
macq at llnl.gov




More information about the R-help mailing list