Kevin Corry
Kevin Corry

Reputation: 155

Reading in data inside a function

Here is a function that i am trying to execute, My data directory and base directory have the correct file paths.

loadDIH = function(){ 
##----
##++++
## Target variable: Days in hospital Year 2
dih.Y2    <- read.csv(file = paste(dataDir, "DaysInHospital_Y2.csv", sep=""),
        colClasses = c("factor", "integer", "integer"),
        comment.char = "")
## Days in hospital Year 3
dih.Y3    <- read.csv(file = paste(dataDir, "DaysInHospital_Y3.csv", sep=""),
        colClasses = c("factor", "integer", "integer"),
        comment.char = "")

   return(list(dih.Y2,dih.Y3))
}

>return(list(dih.Y2,dih.Y3))
Error: object 'dih.Y2' not found

My data directory and base directory have the correct file paths because when i execute the code with out using the function it reads the data eg.

dih.Y2    <- read.csv(file = paste(dataDir, "DaysInHospital_Y2.csv", sep=""),
        colClasses = c("factor", "integer", "integer"),
        comment.char = "")

dih.Y3    <- read.csv(file = paste(dataDir, "DaysInHospital_Y3.csv", sep=""),
        colClasses = c("factor", "integer", "integer"),
        comment.char = "")


>dih.Y2

This returns dih.Y2

Any thought or ideas on how to execute this as a function? I appreciate any help?

Upvotes: 2

Views: 2267

Answers (1)

joran
joran

Reputation: 173727

Objects created inside a function are visible only within that function. You'll want to use an explicit return statement, like

return(list(dih.Y2,dih.Y3))

Moreover, you'd probably benefit from spending some time reading the R manual section on scope.

There is also the global assignment operator <<-, but it's use is often frowned upon. You should probably stick with the way R wants to be used, and have functions return the values you want explicitly.

In your example, it would look like this:

loadDIH = function(){ 
##----
##++++
## Target variable: Days in hospital Year 2
dih.Y2    <- read.csv(file = paste(dataDir, "DaysInHospital_Y2.csv", sep=""),
        colClasses = c("factor", "integer", "integer"),
        comment.char = "")
## Days in hospital Year 3
dih.Y3    <- read.csv(file = paste(dataDir, "DaysInHospital_Y3.csv", sep=""),
        colClasses = c("factor", "integer", "integer"),
        comment.char = "")

   return(list(dih.Y2,dih.Y3))
}

Then the command,

foo <- loadDIH(...)

will result in foo being a list containing dih.Y2 and dih.Y3.

This kind of stuff is covered extensively in some of the manuals for beginners.

Upvotes: 4

Related Questions