###########
x <- 10
fun <- function(var){
x <- var
print(var)
}
print(x)
print(5)
print(x)
##########
###########
x <- 10
fun <- function(var){
x <- var
print(var)
}
print(x)
print(5)
print(x)
##########
Welcome to the community!
Here's the output of your code, and I'll try to explain in the comments in that code that there is nothing wrong with it:
x <- 10 # x is assigned to a value of 10
fun <- function(var){
x <- var
print(var)
}
print(x) # x is still 10
#> [1] 10
print(5) # you're printing a number 5, and it doesn't affect x at all
#> [1] 5
print(x) # x remains at 10
#> [1] 10
Even if you have done print(fun(5))
instead of print(5)
, it won't matter. The changes inside the function are local (withing the environment under fun
), and it will not affect the value of x
in the global environment, unless you explicitly specify so.
If you had used x <<- var
instead of x <- var
inside fun
, then the global value would have been affected.
Hope this helps.
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.
If you have a query related to it or one of the replies, start a new topic and refer back with a link.