I am working on a meta-interpreter for a language fragment that needs to be rich enough to support higher-order functions, and running into a problem with closures.
Specifically, I need all values to be representable as finite terms; no infinite recurrence, no objects pointing to each other. This is fine for most kinds of values, numbers, finite lists, maps, abstract syntax trees representing program code. The problem is closures; they contain a reference to their containing environment, but if a closure is stored in a local variable, then that containing environment also contains a reference to the closure. This is fine if you are working with mutable pointers, but it's an infinite recurrence if you are trying to work with finite terms.
Is there a known technique for representing closures as finite terms, or some technique I am missing that bypasses the problem?
I once had a similar problem when I wrote a functional language that used reference counting GC, and therefore had to avoid any cyclic references.
My solution was that the environment didn't actually include a pointer to the closure. Instead, it stored a function that would produce the closure when you pass it a pointer to the environment.
The process of looking up a value from the environment would include calling that function to produce the closure if necessary. That function, of course, doesn't need a cyclic pointer to the environment, because the environment will be passed in.
This trick is basically making recursive data structures in the same way that the Y combinator is used to make recursive functions.
Is there a function that recreates the grid style environment viewer in RStudio as a data frame? Or is it an accessible object somewhere?
I understand that I could create something similar with a mixture of ls, class, object.size and length functions. But I was wondering if there was a base function or existing method that achieves that same thing?
edit: My problem is not the same as the duplicate suggested as that is regarding looping through global environment and accessing object contents. I am aware I could manually make my own function to make the data frame I would like to know if a function already exists.
I am trying to load some sources to be available in cluster nodes (I'm trying out to do something with ClusterEvalQ from the "parallel" package). The problem I have is that for some reason some of the functions that are normally loaded when I simply use source() from within a script are not loaded when loaded with evalq(). I am trying to source my files that have multiple function definitions in the compute nodes with clusterEvalQ() - apparently there is this "tail" argument in the end of the source function that prevents from loading the last function. How do I go about fixing that?
I have seen there is another question addressing the same issue.
But my problem is different. It loads everything except the last thing defined in the source file.
Thank you for improving the formating guys - I rarelly ask questions on stack overflow.
My current workaround is to put a dummy empty function on the most imporant sources.
The clusterEvalQ function is originally part of the snow package that parallel uses to do some of its parallelization. In that package there are two functions typically used "pass stuff to nodes". These are:
1) clusterEvalQ
This function is used to evaluate expressions on each node. Typically used to load packages through library or require. The snow documentation says:
clusterEvalQ evaluates a literal expression on each cluster node. It a cluster version of evalq, and
is a convenience function deļ¬ned in terms of clusterCall.
I'm not sure how this would work for evaluating a source call on each node, because honestly I've never tried. When I source functions I usually go with...
2) clusterExport
This function passes objects from the current workspace on to the nodes. This can be used in conjunction with source because these functions are part of the workspace just as any other object (you can do that before setting up the cluster, and then pass the sourced functions to the nodes):
clusterExport assigns the values on the master of the variables named in list to variables of the
same names in the global environments of each node.
The list argument is actually a character vector of objects names you want to pass on to the nodes. I usually take the lazy route (because I keep my workspace clean in the first place) and do:
clusterExport(localCl, list=ls())
Hope this helps!
Much has been written here about developing a workflow in R for statistical projects. The most popular workflow seems to be Josh Reich's LCFD model. With a main.R containing code:
source('load.R')
source('clean.R')
source('func.R')
source('do.R')
so that a single source('main.R') runs the entire project.
Q: Is there a reason to prefer this workflow to one in which the line-by-line interpretive work done in load.R, clean.R, and do.R is replaced by functions which are called by main.R?
I can't find the link now, but I had read somewhere on SO that when programming in R one must get over their desire to write everything in terms of function calls---that R was MEANT to be written is this line-by-line interpretive form.
Q: Really? Why?
I've been frustrated with the LCFD approach and am going to probably write everything in terms of function calls. But before doing this, I'd like to hear from the good folks of SO as to whether this is a good idea or not.
EDIT: The project I'm working on right now is to (1) read in a set of financial data, (2) clean it (quite involved), (3) Estimate some quantity associated with the data using my estimator (4) Estimate that same quantity using traditional estimators (5) Report results. My programs should be written in such a way that it's a cinch to do the work (1) for different empirical data sets, (2) for simulation data, or (3) using different estimators. ALSO, it should follow literate programming and reproducible research guidelines so that it's simple for a newcomer to the code to run the program, understand what's going on, and how to tweak it.
I think that any temporary stuff created in source'd files won't get cleaned up. If I do:
x=matrix(runif(big^2),big,big)
z=sum(x)
and source that as a file, x hangs around although I don't need it. But if I do:
ff=function(big){
x = matrix(runif(big^2),big,big)
z=sum(x)
return(z)
}
and instead of source, do z=ff(big) in my script, the x matrix goes out of scope and so gets cleaned up.
Functions enable neat little re-usable encapsulations and don't pollute outside themselves. In general, they don't have side-effects. Your line-by-line scripts could be using global variables and names tied to the data set in current use, which makes them unre-usable.
I sometimes work line-by-line, but as soon as I get more than about five lines I see that what I have really needs making into a proper reusable function, and more often than not I do end up re-using it.
I don't think there is a single answer. The best thing to do is keep the relative merits in mind and then pick an approach for that situation.
1) functions. The advantage of not using functions is that all your variables are left in the workspace and you can examine them at the end. That may help you figure out what is going on if you have problems.
On the other hand, the advantage of well designed functions is that you can unit test them. That is you can test them apart from the rest of the code making them easier to test. Also when you use a function, modulo certain lower level constructs, you know that the results of one function won't affect the others unless they are passed out and this may limit the damage that one function's erroneous processing can do to another's. You can use the debug facility in R to debug your functions and being able to single step through them is an advantage.
2) LCFD. Regarding whether you should use a decomposition of load/clean/func/do regardless of whether its done via source or functions is a second question. The problem with this decomposition regardless of whether its done via source or functions is that you need to run one just to be able to test out the next so you can't really test them independently. From that viewpoint its not the ideal structure.
On the other hand, it does have the advantage that you may be able to replace the load step independently of the other steps if you want to try it on different data and can replace the other steps independently of the load and clean steps if you want to try different processing.
3) No. of Files There may be a third question implicit in what you are asking whether everything should be in one or multiple source files. The advantage of putting things in different source files is that you don't have to look at irrelevant items. In particular if you have routines that are not being used or not relevant to the current function you are looking at they won't interrupt the flow since you can arrange that they are in other files.
On the other hand, there may be an advantage in putting everything in one file from the viewpoint of (a) deployment, i.e. you can just send someone that single file, and (b) editing convenience as you can put the entire program in a single editor session which, for example, facilitates searching since you can search the entire program using the editor's functions as you don't have to determine which file a routine is in. Also successive undo commands will allow you to move backward across all units of your program and a single save will save the current state of all modules since there is only one. (c) speed, i.e. if you are working over a slow network it may be faster to keep a single file in your local machine and then just write it out occasionally rather than having to go back and forth to the slow remote.
Note: One other thing to think about is that using packages may be superior for your needs relative to sourcing files in the first place.
No one has mentioned an important consideration when writing functions: there's not much point in writing them unless you're repeating some action again and again. In some parts of an analysis, you'll being doing one-off operations, so there's not much point in writing a function for them. If you have to repeat something more than a few times, it's worth investing the time and effort to write a re-usable function.
Workflow:
I use something very similar:
Base.r: pulls primary data, calls on other files (items 2 through 5)
Functions.r: loads functions
Plot Options.r: loads a number of general plot options I use frequently
Lists.r: loads lists, I have a lot of them because company names, statements and the like change over time
Recodes.r: most of the work is done in this file, essentially it's data cleaning and sorting
No analysis has been done up to this point. This is just for data cleaning and sorting.
At the end of Recodes.r I save the environment to be reloaded into my actual analysis.
save(list=ls(), file="Cleaned.Rdata")
With the cleaning done, functions and plot options ready, I start getting into my analysis. Again, I continue to break it up into smaller files that are focused into topics or themes, like: demographics, client requests, correlations, correspondence analysis, plots, ect. I almost always run the first 5 automatically to get my environment set up and then I run the others on a line by line basis to ensure accuracy and explore.
At the beginning of every file I load the cleaned data environment and prosper.
load("Cleaned.Rdata")
Object Nomenclature:
I don't use lists, but I do use a nomenclature for my objects.
df.YYYY # Data for a certain year
demo.describe.YYYY ## Demographic data for a certain year
po.describe ## Plot option
list.describe.YYYY ## lists
f.describe ## Functions
Using a friendly mnemonic to replace "describe" in the above.
Commenting
I've been trying to get myself into the habit of using comment(x) which I've found incredibly useful. Comments in the code are helpful but oftentimes not enough.
Cleaning Up
Again, here, I always try to use the same object(s) for easy cleanup. tmp, tmp1, tmp2, tmp3 for example and ensuring to remove them at the end.
Functions
There has been some commentary in other posts about only writing a function for something if you're going to use it more than once. I'd like to adjust this to say, if you think there's a possibility that you may EVER use it again, you should throw it into a function. I can't even count the number of times I wished I wrote a function for a process I created on a line by line basis.
Also, BEFORE I change a function, I throw it into a file called Deprecated Functions.r, again, protecting against the "how the hell did I do that" effect.
I often divide up my code similarly to this (though I usually put Load and Clean in one file), but I never just source all the files to run the entire project; to me that defeats the purpose of dividing them up.
Like the comment from Sharpie, I think your workflow should depends a lot on the kind of work you're doing. I do mostly exploratory work, and in that context, keeping the data input (load and clean) separate from the analysis (functions and do), means that I don't have to reload and reclean when I come back the next day; I can instead save the data set after cleaning and then import it again.
I have little experience doing repetitive munging of daily data sets, but I imagine that I would find a different workflow helpful; as Hadley answers, if you're only doing something once (as I am when I load/clean my data), it may not be helpful to write a function. But if you're doing it over and over again (as it seems you would be) it might be much more helpful.
In short, I've found dividing up the code helpful for exploratory analyses, but would probably do something different for repetitive analyses, just like you're thinking about.
I've been pondering workflow tradeoffs for some time.
Here is what I do for any project involving data analysis:
Load and Clean: Create clean versions of the raw datasets for the project, as if I was building a local relational database. Thus, I structure the tables in 3n normal form where possible. I perform basic munging but I do not merge or filter tables at this step; again, I'm simply creating a normalized database for a given project. I put this step in its own file and I will save the objects to disk at the end using save.
Functions: I create a function script with functions for data filtering, merging and aggregation tasks. This is the most intellectually challenging part of the workflow as I'm forced to think about how to create proper abstractions so that the functions are reusable. The functions need to generalize so that I can flexibly merge and aggregate data from the load and clean step. As in the LCFD model, this script has no side effects as it only loads function definitions.
Function Tests: I create a separate script to test and optimize the performance of the functions defined in step 2. I clearly define what the output from the functions should be, so this step serves as a kind of documentation (think unit testing).
Main: I load the objects saved in step 1. If the tables are too big to fit in RAM, I can filter the tables with a SQL query, keeping with the database thinking. I then filter, merge and aggregate the tables by calling the functions defined in step 2. The tables are passed as arguments to the functions I defined. The output of the functions are data structures in a form suitable for plotting, modeling and analysis. Obviously, I may have a few extra line by line steps where it makes little sense to create a new function.
This workflow allows me to do lightning fast exploration at the Main.R step. This is because I have built clear, generalizable, and optimized functions. The main difference from the LCFD model is that I do not preform line-by-line filtering, merging or aggregating; I assume that I may want to filter, merge, or aggregate the data in different ways as part of exploration. Additionally, I don't want to pollute my global environment with lengthy line-by-line script; as Spacedman points out, functions help with this.
Background
I written an R package, and now a collaborator (recent CS grad who is new to R) is editing and refactoring the code. In the process, he is dividing up my functions into smaller, more generic functions.
What he is doing makes sense, but when I started with package.skeleton(), I had one file per function. Now, he has added functions on which the primary function depends, but that may have limited use outside the function itself.
He suggests that all the functions go into a single file, but I am against that because it is easier to do version control when we work on different files.
I have since started using roxygen to document each function within the text.
Question
What is the recommended way to handle functions: clearly the helper functions should stay with the the main function, but to what extent do I need to document helper functions?
The #export suggestion in the comments is helpful, but I am curious to know how others organize their code.
I cut up my functions under two conditions :
when it improves readibility of the code of the main function, and/or
when it avoids copy-pasting code, eg if the same code is used a couple of times within the same function.
I do include the so-called helper functions in the file of the main function, but only as long as those helper functions are not used in any other function. Actually, I consider them nested within the main function. I do understand your argument for version control, but changing the helper function comes down to changing the performance of the main function, so I see no problem in keeping them in the same file.
Some helper functions might be used in different other functions, and then I save them in their own file. Often I do export those functions, as they might be of interest for the user. Compare this to eg lm and the underlying lm.fit, where advanced users could make decent use of lm.fit for speeding up code etc.
I use the naming convention used in quite some packages (and derived from linux), by preceding every "hidden" function by a dot. So that makes
.helper.function <- function(x, ...){
... some code ...
}
main.function <- function(x, ...){
...some code, including .helper.function(y, ...)
}
I explicitly #export all functions that need exporting, never the helper functions. It's not always easy to judge whether a function might be of interest to an end user, but in most cases it's pretty clear.
To give an example : A few lines of code to cut off NA lines I consider a helper function. A more complex function to convert the dataset to the correct format I export and document.
YMMV