简体   繁体   中英

Reading a File by passing a parameter to function in R

I am trying to read a file be by passing parameter to a function in R. The same syntax works outside the function but not in it.

> corr <- function(directory){
z <- sprintf("C:\\Users\\rajat\\Documents\\education\\Coursera\\Computing for Data  Analysis\\%s\\001.csv",directory)
print(z)
data2<-read.csv(z)
}
corr(directory="specdata")
[1] "C:\\Users\\rajat\\Documents\\education\\Coursera\\Computing for Data Analysis\\specdata\\001.csv"
> data2
> Error: object 'data2' not found

The one without using function gives proper result.

  > directory="specdata"
  > z <- sprintf("C:\\Users\\rajat\\Documents\\education\\Coursera\\Computing for Data Analysis\\%s\\001.csv",directory)
  > print(z)
  [1] "C:\\Users\\rajat\\Documents\\education\\Coursera\\Computing for Data Analysis\\specdata\\001.csv"
  > data1<-read.csv(z)

  > str(data1)
  'data.frame': 1461 obs. of  4 variables:
  $ Date   : Factor w/ 1461 levels "2003-01-01","2003-01-02",..: 1 2 3 4 5 6 7 8 9 10 ...

data2 just exists in the environment of your corr function. To make it globally available, do data2<<-read.csv(z) . Then it will be found outside the function. More info: http://stat.ethz.ch/R-manual/R-patched/library/base/html/assignOps.html

Disclaimer : A cleaner way would be to return the data from the function like this:

corr <- function(directory) {
  z <- sprintf("C:\\Users\\rajat\\Documents\\education\\Coursera\\Computing for Data  Analysis\\%s\\001.csv",directory)
  print(z)
  return(read.csv(z))
}

data2 <- corr(directory="specdata")
data2

See @thelatemail's comment below.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM