-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
- Create functions for commonly re-used code
- store code in known paths so that we can easily include it in other functions.
- Rule: if a given operation (simple mathematical or complex function) occurs more than once in a code base (i.e. it is used in multiple places or by multiple people), create a function for that operation, stored in a central location (can be loaded via
source()). - Package/Functionalize - Once a function is widely used and crucial, it can be good to make it part of a package, to avoid excessive
source()calls
- Functions must have granular specificity
- At minimum separate data Retrieval/Modification, Analysis, Visualization, and Export
- functions that have combined code for these 3 operations are difficult to modularize and expand/build-upon.
- Most important to separate data retrieval first. Data sets should be passed in to analysis and visualization functions under all circumstances.
- Save() operations should also be separate from other functions When we retrieve data, analyze it, and visualize in separate functions, we should also save them in separate functions if at all possible.
- Always Declare Variables at the Top of the Script/function
- Never, ever, ever use
implicitglobal variables in a function no matter what you are faced with!!
Ex 2: Implicit globals work, but they create code that is not portable and can fail unexpectedly, and introduce unexpected data.
my_fun <- function(x, y) {
rez <- x + y + z
return(rez)
}
x=45
y=10
z=12
my_fun(x,y)
z=92
# [1] 67
my_fun(x,y)
[1] 147
# now clear z, as if someone else loaded your function and saw x and y as args
rm(z)
my_fun(x,y)
# > Error in my_fun(x, y) : object 'z' not found
- Return Graphic objects as variables: When using ggplot (and maybe plot?), a graph should be stored in a variable, then rendered in a separate line, examples:
- slow but fancy:
# Create a variable with a plot in it, this will NOT display immediately
myDiamonds <- ggplot(diamonds, aes(x=carat, y=price)) + geom_point(aes(color=cut))
# Show the plot
myDiamonds
# Add a loess type curve to the plot
myDiamonds + geom_smooth()
- Fast and basic -- save any plot at any time:
# create the plot and stash in plot1
plot1 <- ggplot(mtcars, aes(x=cyl)) + geom_bar()
# saves the last plot.
ggsave("myggplot.png")
# Save a specific plot in any variable
ggsave("myggplot.png", plot=plot1)
Metadata
Metadata
Assignees
Labels
No labels