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?