How to make object created within function usable outside How to make object created within function usable outside r r

How to make object created within function usable outside


That's easy: use <<- for assignment to a global.

But then again, global assignment is evil and not functional. Maybe you'd rather returna list with several results from your function? Looking at your code, it seems that your second function may confuse the return and print. Make sure you return the correct data structure.


A little about functional programming. First of all, when you define your function:

getTitles <- function(pages) {  [...]  return(my.matrix)  print(my.matrix)}

know that when the function is called it will never reach the print statement. Instead, it will exit right before, with return. So you can remove that print statement, it is useless.

Now the more important stuff. Inside your function, you define and return my.matrix. The object only exists within the scope of the function: as the function exits, what is returned is an unnamed object (and my.matrix is lost.)

In your session, when you call

getTitles(mypages)

the result is printed because you did not assign it. Instead, you should do:

out.matrix <- getTitles(mypages)

Now the result won't be printed but you can definitely do so by typing print(out.matrix) or just out.matrix on a single line. And because you have stored the result in an object, you can now reuse it for further manipulations.

If it help you grasp the concept, this is all the same as calling the c() function from the command line:

c(1, 5, 2)      # will return and print a vector x <- c(1, 5, 2) # will return and assign a vector (not printed.)

Bonus: Really, I don't think you need to define getTitles, but you can use one of the *apply functions. I would try this:

url    <- as.character(mypages)title  <- sapply(url, getTitle)report <- data.frame(url, title)write.csv(report, file = "report.csv", row.names = FALSE)


Can't you just use <<- to assign it the object to the workspace? The following code works for me and saves the amort_value object.

amortization <- function(cost, downpayment, interest, term) {  amort_value <<- (cost)*(1-downpayment/100)*(interest/1200)*((1+interest/1200)^(term*12))/((1+interest/1200)^(term*12)-1)  sprintf("$%.2f", amort_value)         }amortization(445000,20,3,15)amort_value