This one cost me more time to figure out than it should have. The reason being, it turns out that I never properly understood what the
source() function does.
So here is the story: I was setting up a shiny server for a student based on her code. She was running the shiny app from within RDesktop, and so before starting the app with
runApp() she would load all necessary object and
source() a file called
helpers.R with some common calculations.
In order to put the app on a server, I have moved these pre-runApp() initializations into
server.R. Suddenly, weird errors appeared. The functions in the
helpers.R no longer seemed to be able to find anything in the parent environment — object X not found! Even though I called
source() immediately after loading the necessary objects into the environment:
# file server.R
The solution was, as usual, to read documentation. Specifically, documentation on
local TRUE, FALSE or an environment, determining where the
parsed expressions are evaluated. FALSE (the default)
corresponds to the user's workspace (the global
environment) and TRUE to the environment from which
source is called.
The objects which I have
load()-ed before were not in the global environment, but instead in another environment created by shiny. However, the expressions from
helpers.R were evaluated in the global environment. Thus, a new function defined in
helpers.R could be seen from inside
server.R, but an object loaded from
server.R could not be seen by
It is the first time that I have noticed this. Normally, I would use a file such as
helpers.R only to define helper functions, and actually call them from
ui.R. However, I was thinking that
source() is something like
#include in C, simply calling the commands in the given file as if they were inserted at this position into the code — or called from the environment from which
source() was called.
This is not so.