how to get output from a function

Hi ,
I'm new to R. I have written a small function, but i can't figure out why the output doesn't get pass through

get_symbols<-function(){
wheel<-c("DD", "7","BBB","BB","B", "C","0")
symbols<-sample(wheel, size = 3, replace=TRUE),
prob =c(0.03, 0.03, 0.06, 0.1, 0.25, 0.01, 0.52))
}

get_symbols()
symbols

When I run the code symbols always equal to [0,0,0] while get_symbols() gives different results.
Why the function output doesn't get assigned to symbols?

I can recommend going over this book to get more familiar with how things work in R:

Specifically chapter on functions might be useful for you:

As is, your function won't work since you have a mistake in symbols <- line. If you correct this mistake, it works exactly as you expect:

set.seed(42)
get_symbols<-function(){
  wheel <- c("DD", "7","BBB","BB","B", "C","0")
  sample(wheel, size = 3, replace=TRUE, prob =c(0.03, 0.03, 0.06, 0.1, 0.25, 0.01, 0.52))
}

get_symbols()
#> [1] "BBB" "DD"  "0"

symbols <- get_symbols()
symbols
#> [1] "BB" "B"  "0"

Created on 2020-04-30 by the reprex package (v0.3.0)

3 Likes

Thanks! Actually I was reading the book you recommend and tried to write the code in my own way :slight_smile:
As you said, there are two errors with my script:

  1. the first error is the typo with "(",
  2. the 2nd error is the last line of the code must generate an output, a code like " symbols<-sample(wheel, size = 3, replace=TRUE, prob =c(0.03, 0.03, 0.06, 0.1, 0.25, 0.01, 0.52))" will not generate an output, it simply assigns a value to symbol object, however, this object is only saved in run-time environment.
    The get_symbols() function will not save this result to Global Environment as it's not an calculation output, hence symbol object remains 0 in Global Environment.

Thanks!

1 Like

You are almost correct, but I just wanted to clarify a few things so that there is no misconception as you are learning.

Technically, output of an R function is the last evaluated expression. This means that this code will work and produce output that you want:

set.seed(42)
get_symbols<-function(){
  wheel <- c("DD", "7","BBB","BB","B", "C","0")
  symbols <- sample(wheel, size = 3, replace=TRUE, prob =c(0.03, 0.03, 0.06, 0.1, 0.25, 0.01, 0.52))
}

symbols <- get_symbols()

symbols
#> [1] "BBB" "DD"  "0"

Created on 2020-05-01 by the reprex package (v0.3.0)

You are right, though, that everything that is created inside of a function will remain there. However, unless you define the symbols object in your Global environment, it's value will be not defined and not 0. The reason you were getting [1] 0 0 0 output is because of randomness in your function and since "0" has 0.52 weight.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.