Can R use source () to avoid changing a variable?

Here is my temp.R

a=1
print(a)

but when I use the source ("temp.R"), the variable a is replaced

> a=3
> source("temp.R")
[1] 1
> a
[1] 1

And I expect that

> a=3
> source("temp.R")
[1] 1
> a
[1] 3

Can this be done in R? Any help to get the result, as described above, would be greatly appreciated.

+4
source share
1 answer

Rate the expression in its own environment:

# write out the file to be sourced
fLS = file(description = "Code/8-LocalSource-Input.R", open = "w+")
write(x ="a = 1; print(a)", file = fLS)
close(fLS)

# source the file
a = 3
sourceEnv = new.env()
with(sourceEnv, source("Code//8-LocalSource-Input.R", local = TRUE))
a
+4
source

All Articles