0

I'm very new to R and asking questions on StackOverflow, so I apologize in advance if something is unclear or I'm asking a silly question.

I am trying to define a function. When executing the function, a variable (prize) should be created with a specific value (3), iff a different variable (symbols) contains only one unique value. I'm doing it this way because I'm following the exercises in "Hands on Programming with R", by Garret Grolemund. (chapter 7).

Assigning values to symbols is fine and my if statement returns the correct value for prize when I take it out of the function() definition.

symbols <- c("DD", "DD", "DD")

if (all(symbols == symbols[1])) {
     prize <- 3
   }

prize 
[3]

The problem appears when I put the if statement into a function() definition, like so:

symbols <- c("DD", "DD", "DD")

prize <- 100

score <- function() {
 if (all(symbols == symbols[1])) {
     prize <- 3
   }
 }

score()
prize
[100]

If I call prize after score() I just get the value that I manually assigned prize before running the function score() : 100.

I realize that I'm programming the function score() without any arguments (in function( arg). But if I'm not mistaken this shouldn't be a problem?

Thanks for your response.

EDIT: After some further testing I seems that it's because any variables created in a function are only there in the function itself, and not in the global environment? Is that correct?

FinnFiana
  • 43
  • 5
  • 2
    R is a functional language. One of the core ideas of a functional language is that when you run a function, it should not modify your global environment. Functions should return new values, not change a global state. Basically this type of behavior is discouraged, though it is technically possible with the `<<-` assignment operator rather than `<-`. But it would be better for your function to return a value that you can then assign to a variable if you want – MrFlick Jun 29 '22 at 13:54
  • Hey, thanks that explains it! – FinnFiana Jun 29 '22 at 14:09
  • as @MrFlick said it is bad practise to let your function influence your global environment (it will get messy). But if you want to see the result of a variable that is defined inside your function you could use ```return(prize)``` 1 line above the last parenthesis of your function – Omniswitcher Jun 29 '22 at 14:09

0 Answers0