On Fri, Aug 6, 2010 at 9:29 AM, Raghuraman Ramachandran
<optionsraghu at gmail.com> wrote:> Hi
>
> I wish to read a file from my local directory from inside a function. I am
> passing the filename as the argument but this does not work.
> Say for example
> function(dat)
> {
> dat1=read.csv("D:\\dat.csv",header=TRUE)
this does not work because in the quoted string, 'dat' is not
evaluated. You have several options, one as shown by Wu Gong, simply
pass the entire file path as the argument to your function.
Alternately, suppose your data files are always located at D:\\ and
always end in .csv you could do this which paste()s D:\\ and .csv to
the front and end, respectively, of 'dat'.
myfun <- function(dat) {
filename <- paste("D:\\", dat, ".csv", sep =
"")
read.csv(file = filename, header = TRUE)
}
myfun("datafilename") #or whatever the filename is
HTH,
Josh
> }
> If I call funtion(dat) I get the following error. 'Intuitively' i
understand
> this is a mistake but how do I overcome this and how can I read a file name
> passed as an argument please?
>
>
> Error in file(file, "rt") : cannot open the connection
> In addition: Warning message:
> In file(file, "rt") :
> ?cannot open file 'D:\dat.csv': No such file or directory
>
> Many thanks
> Raghu
>
> ? ? ? ?[[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>
--
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/