1

I wrote a function in R that returns a list composed of two variables. The function works correctly in that the correct values are returned. The problem, however, is that I can't then access the list for further processing. The code is this:

grinder <- function(x) {

if(x == "BID") {
miles <- 18.4 * n.row
tolls <- 1.8 * n.row

} else if(x == "SPR") {
miles <- 10.8 * n.row
tolls <- 0

} else if (x == "BRI") {
miles <- 3.8 * n.row
tolls <- 0

} else if (x == "GOO") {
miles <- 66.2 * n.row
tolls <- 1.8 * n.row

} else if (x == "MIL") {
miles <- 108
tolls <- 0

} else if (x == "SMH") {
miles <- 94.6 * n.row
tolls <- 2 * n.row

}

mil.tol <- list(miles,tolls)
return(mil.tol)

}

grinder(x)

The correct values are returned, but I can't then access mil.tol to do anything with those values. Nor can I get correct values for miles or tolls. The console returns this:

> mil.tol
Error: object 'mil.tol' not found
> miles

Any suggestions?

hopnoggin
  • 23
  • 2
  • 1
    mil.tol <- grinder(x) and then access it – milos.ai Feb 12 '16 at 16:41
  • You should expect `grinder` to work like any normal R function. This means it doesn't just "create" objects for you, you assign the result to an object. If you run a linear model `lm(mpg ~ wt, data = mtcars)` it would be **terrible** if that created an object in your workspace called "model" - you couldn't ever work with more than one model at a time. Just like you're used to naming and assigning your models `mod1 <- lm(...)`, you need to name and assign the output of your function: `mil.tol <- grinder(x)` – Gregor Thomas Feb 12 '16 at 20:41

1 Answers1

0

miles, tolls and mil.tol are all local to the function and are not returned, but you can assign the output of the function (i.e. from the return()) like below to mil.tol:

mil.tol <- grinder(x)

Would recommend also reading this SO post here

Community
  • 1
  • 1
Sam Gilbert
  • 1,642
  • 3
  • 21
  • 38