This question already has an answer here:
ggplot's qplot does not execute on sourcing
(1 answer)
Closed 9 years ago.
Consider a source file of this form:
# initialize the function
f = function() {
# ...
}
# call the function
f()
In python, the import function would load and executes the file; however in R, the source command does initialize functions defined by the source file, but does not call the functions if they are called in the file.
Is there any R command (or option) to import and execute the file?
Thanks for your help.
?source states:
Description:
‘source’ causes R to accept its input from the named file or URL
or connection. Input is read and ‘parse’d from that file until
the end of the file is reached, then the parsed expressions are
evaluated sequentially in the chosen environment.
Therefore,
source is the function you are looking for,
I refute your claim - source works for me as per the documentation
If you are not seeing the documented behaviour then there must be a different problem that you are not telling us.
How are you deducing that source is not executing your f?
I can think of one scenario that you may not be aware of, which is documented in ?source, namely:
Details:
Note that running code via ‘source’ differs in a few respects from
entering it at the R command line. Since expressions are not
executed at the top level, auto-printing is not done. So you will
need to include explicit ‘print’ calls for things you want to be
printed (and remember that this includes plotting by ‘lattice’,
FAQ Q7.22).
Not seeing the output from objects called by name or grid graphics-based plots not showing are symptoms of auto-printing not being active as the evaluation is not occurring at the top-level. You need to explicitly print() objects, including grid-based graphics like Lattice and ggplot2 figures.
Also note the print.eval argument, which will default to
> getOption("verbose")
[1] FALSE
which may also be of use to you.
Related
I have a somewhat niche question that I'm hoping someone can answer for me or help me find a work-around to:
I've written a script in R that will run an ImageJ macro for sets of images I produce as a part of my workflow.
Because this is work that I may publish at some point or may be used by other researchers in the lab after me, I like to keep a copy of the R script and ImageJ macro within each dataset's folder as I sometimes modify the script a little for a certain series of images and this makes it very clear which version of code I used to process which set of images.
I am somewhat new to coding so I'm slowly trying to make this piece of code more streamlined and to have fewer places within the script that need to be modified each time I copy it to a new datafile, which is where I'm running into an issue.
In the script, I call the macro using the following code:
macro <- function(i) {
system2('/Applications/Fiji.app/Contents/MacOS/ImageJ-macosx', args=c('-batch "/Users/xxxx/yyyy/zzzz/current experiment/ImageJ Macro.ijm"', i))
}
For each new project I need to edit the filepath manually. I would love a way to define a variable at the beginning of the script which could be passed into the arguments as a string, but I can't figure out how to do it.
I've tried creating a variable just for the filepath, but R can't recognize a variable as part of the string that includes '-batch...'
I've also tried creating a variable containing the entire string that needs to be passed to args, but that doesn't work either. Here's what I coded for that attempt:
ImageJMacro <- paste(getwd(),"/ImageJ Macro.ijm",sep="")
batch1 = sprintf('-batch "%s"', ImageJMacro)
batchline = sprintf("'%s'", batch1)
As you can see, I had to do this in two steps because the single quotes outside of double quotes was giving an error. I thought this would work because when I run:
cat(batchline)
The string looks correct, but when passed into the arguments clause of the system command like so:
macro <- function(i) {
system2('/Applications/Fiji.app/Contents/MacOS/ImageJ-macosx', args=c(batchline, i))
}
it still throws an error.
Any ideas? Other solutions I should try? Thanks in advance for your help, I appreciate it!
Editing to add additional clarification as requested by #rmagn0:
ImageJ is an image analysis software which allows you to write 'macros', hard-coded scripts of repetitive analyses and apply them across many images. I'm not including the ImageJ macro code here because it's not relevant to my question. Suffice it to say that it expects to receive a string argument input, which it then parses out into several components used in the image processing. These string components are parsed out using an asterisk as a delimiter as described in this stack overflow: Calling an ImageJ Macro from R
I am trying to use R to pass a list of arguments to my ImageJ macro, one for each data file I need analyzed, as demonstrated in the code above. Note on above: I named the function in R 'macro', but it is really just calling the command line instance of my ImageJ macro.
If I were to run one instance of the list in the command line, it would look like this:
Contents/MacOS/ImageJ-macosx -batch "/Users/xxxx/yyyy/zzzz/current experiment/ImageJ Macro.ijm" ImageName.tif*Xcoord*Ycoord*/Users/xxxx/yyyy/zzzz/InputDirectory*/Users/xxxx/yyyy/zzzz/OutputDirectory*Suffix
I can run julia script with arguments from Powershell as > julia test.jl 'a' 'b'. I can run a script from REPL with include("test.jl") but include accepts just one argument - the path to the script.
From playing around with include it seems that it runs a script as a code block with all the variables referencing the current(?) scope so if I explicitly redefine ARGS variable in REPL it catches on and displays corresponding script results:
>ARGS="c","d"
>include("test.jl") # prints its arguments in a loop
c
d
This however gives a warning for redefining ARGS and doesn't seem the intended way of doing that. Is there another way to run a script from REPL (or from another script) while stating its arguments explicitly?
You probably don't want to run a self-contained script by includeing it. There are two options:
If the script isn't in your control and calling it from the command-line is the canonical interface, just call it in a separate Julia process. run(`$JULIA_HOME/julia path/to/script.jl arg1 arg2`). See running external commands for more details.
If you have control over the script, it'd probably make more sense to split it up into two parts: a library-like file that just defines Julia functions (but doesn't run any analyses) and a command-line file that parses the arguments and calls the functions defined by the library. Both command-line interface and the second script your writing now can include the library — or better yet make the library-like file a full-fledged package.
This solution is not clean or Julia style of doing things. But if you insist:
To avoid the warning when messing with ARGS use the original ARGS but mutate its contents. Like the following:
empty!(ARGS)
push!(ARGS,"argument1")
push!(ARGS,"argument2")
include("file.jl")
And this question is also a duplicate, or related to: juliapassing-argument-to-the-includefile-jl as #AlexanderMorley pointed to.
Not sure if it helps, but it took me a while to figure this:
On your path "C:\Users\\.julia\config\" there may be a .jl file called startup.jl
The trick is that not always Julia setup will create this. So, if neither the directory nor the .jl file exists, create them.
Julia will treat this .jl file as a command list to be executed every time you run REPL. It is very handy in order to set the directory of your projects (i.e. C:\MyJuliaProject\MyJuliaScript.jl using cd("")) and frequent used libs (like using Pkg, using LinearAlgebra, etc)
I wanted to share this as I didn't find anyone explicit saying this directory might not exist in your Julia device's installation. It took me more than it should to figure this thing out.
Hello i'm trying this for loop in which i enable multiple libraries in r.
lbs<-c("plyr","dplyr","magrittr","readr")
for (i in 1:length(lbs)) {
library(lb[i])
}
but i get this error
Error in library(lb[i]) : 'package' must be of length 1
My questions covers two dillemas.
How do i use strings stored in vectors to use them in another function?
How do i tell rstudio to enable certain libraries by default every time in open r.
In short:
The library() function is weird. Try library(lb[i],character.only = TRUE). There is an example illustrating this at the very bottom of ?library, for what it's worth.
Read ?Startup, in particular about using .Rprofile files.
I have a user defined function in R
blah=function(a,b){
something with a and b
}
is it possile to put this somewhere so that I do not need to remember to load in the workspace every time I start up R? Similar to a built in function like
summary(); t.test(); max(); sd()
You can put the function into your .rprofile file.
However, be very careful with what you put there, since it essentially makes your code non-reproducible — it now depends on your .rprofile:
Let’s say you have an R code file performing some analysis, and the code uses the function blah. Executing the code on any other system will fail due to the non-existence of the blah function.
As a consequence, this file should only contain system-specific setup. Don’t define helper functions in there — or if you do, make them defined only in interactive sessions, so that you have a clear environment when R is running a non-interactive script:
if (interactive()) {
# Helper functions go here.
}
And if you find yourself using the same helper functions over and over again, bundle them into packages (or modules) and reuse those.
I am creating an R package, and found it useful to break parts of the logic in one file into internal helper functions, which I define in the same file. I have sort of a special case where my function decides which helper function to use via match.fun(). Since they won't be useful to other functions or people, I don't want to put these in separate files, and I don't want to export them.
All my testthat cases pass using test_dir(). When I don't export these functions, my testthat cases fail during R CMD check.
"object 'helperfunction1' of mode 'function' was not found", quote(get(as.character(FUN),
mode = "function", envir = envir)))
After looking at this post, I am able to get things to work if I explicitly export or add export entries to NAMESPACE, but again I don't want to export these.
Is there a better way to do this and doesn't require me to export? (I'll admit that the source of the issue may be match.fun() and am open to other ways of calling functions at runtime.)
From memory it wasn't clear in the documentation last time I read it (it may have changed), but it will work correctly (without having to export) so long as everything is in the right directories:
You should have a file:
tests/run-all.R
That looks like:
library(testthat)
library(myPackage)
test_package("myPackage")
Then your individual test files should be in the directory inst/tests
These will be run when you do R CMD check, otherwise you can call test_package("myPackage") in R manually.