How to use strings stored in vectors in another function - r

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.

Related

How can I feed a string that includes quotes to a system2 call in R?

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

Load() function in R with an input

I am using R to create a function that allows me to load specific Rdata.
So I have several different files, each containing a specific Rdata set. For instance, if I want to load the information about the northern line, I would write
load(“TfL/Line/northern/Arrivals.Rdata")
And if I want circle line, I would write
load(“TfL/Line/circle/Arrivals.Rdata")
The question is, can I write a function that takes the name of the tube line, say LineName,as an input, using the load function? I tried
Get_information<- function(LineName==NULL){
load(“TfL/Line/LineName/Arrivals.Rdata")}
This doesn’t work. Could someone help me deal with this? Thanks!
You need to pass 'LineName' as a variable. Currently you're just writing "LineName" as a string-literal.
There are a few functions which can do this:
Paste0
Paste0 combines character vectors (literals or objects) into a single string:
load(paste0(“TfL/Line/", LineName, "/Arrivals.Rdata"))
Glue
Glue is a CRAN package which functions in a similar way to paste0, but can be easier to write and read:
#install.packages("glue") #<- run if you don't have glue installed
require("glue") # attach the package so that we can use 'glue'
load(glue("TfL/Line/{LineName}/Arrivals.Rdata"))
If run either of those inside your function, it will work as intended.

R package: Refresh/Update internal raw data

I am developing a package in R (3.4.3) that has some internal data and I would like to be able to let users refresh it without having to do too much work. But let me be more specific.
The package contains several functions that rely on multiple parameters but I am really only exporting wrapper functions that do all the work. Because there is a large number of parameters to pass to those wrapper functions, I am putting them in a .csv file and passing them as a list. The data is therefore a simple .csv file called param.csv with the names of the parameters in one column and their value in the next column
parameter_name,parameter_value
ticker, SPX Index
field, PX_LAST
rolling_window,252
upper_threshold,1
lower_threshold,-1
signal_positive,1
signal_neutral,0
signal_negative,-1
I process it running
param.df <- read.csv(file = "param.csv", header = TRUE, sep = ",")
param.list <- split(param.df[, 2], param.df[, 1])
and I put the list inside the package like this
usethis::use_data(param.list, overwrite = TRUE)
Then, when reset the R interactive window and execute
devtools::document()
devtools::load_all()
devtools::install()
require(pkg)
everything works out great, the data is available and can be passed to functions.
First problem: when I change param.csv, save it and repeat the above four lines of code, the internal param.list is not updated. Is there something I am missing here ? Or is it by nature that the developer of the package should run usethis::use_data(param.list, overwrite = TRUE) each time he changes the .csv file where the data comes from?
Because it is intended to be a sort of map, the users will want to tweak parameters for (manual) model calibration. To try and solve this issue I let users provide the functions with their own parameter list (as a .csv file like before). I have a function get_param_list("path/to/file.csv") that does exactly the same processing that is done above and returns the list. It allows the users to pass their own parameter list. De facto, the internal data param.list is considered a default setting of parameters.
Second Problem: I'd like to let users modify this default list of parameters param.list from outside the package in a safe way.
So since the internal object is a list, the users can simply modify the element of their choice in the list from outside the package. But that is pretty dangerous in my mind because users could
- forget parameters, so I have default values inside the functions for that case
- replace a parameter with another type which can provoke an error or worse, side effects.
Is there a way to let users modify the internal list of parameters without opening the package ? For example I had thought about a function that could replace the .csv file by a new one provided by the user but this brings me back to the First Problem, when I restart the R prompt and reinstall the package, nothing happens unless I usethis::use_data(param.list, overwrite = TRUE) from inside the package. Would another type of data be more useful (e.g. make the data internal) ?
This is my first question on this website but I realize it's quite long and might be taken as a coding style question. But if anyone can see an obvious mistake or misunderstanding of package development in R from my side that would really help me.
Cheers

How to check for accidentally redefining a function name in R

I'm writing some fairly involved R code spread across multiple files and collected together into a package. A problem I've run into on occasion is that I will define a utility function in one file that has the same name as another utility function defined in another file. One of the two definitions gets replaced, leading to unintended behavior. Is there any sort of tool to check for this kind of accidental redefinition? Something that would check that no two top-level assignments foo <- ... in the package assign to the same name?
As pointed out in the comments, the right way to do this is to use packages. Packages give functions their own namespaces automatically, plus they make it very easy to reuse and share code. If you're using RStudio, you can create one with very little effort from the New Project menu.
However, if you can't use packages or namespaces for some reason, there's still a way to do what you want: you can lock a variable (including a function) so that it's not possible to overwrite it.
> pin <- 11
> lockBinding("pin", .GlobalEnv)
> pin <- 12
Error: cannot change value of locked binding for 'pin'
See Binding and Environment Locking for details.

Load AND execute R source file [duplicate]

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.

Resources