Fix function in R for Ubuntu not working properly - r

I have been using R in the terminal window for Ubuntu. Recently I discovered the fix function in R, which I could use to edit my function. However, whenever I use the fix function, it opens up an editor (VIM) and I can use that to write my function. Then I type "wq" to save the work, however when I type the name of the function, it shows that there weren't any edits which were made to the function. Why does this happen?

In order to use the editing functionality, make sure you have either
the default editor installed (do eg grep EDITOR /etc/R/Renviron)
or set the EDITOR environment variable to a different editor you prefer,
or at runtime set options("editor"=....) to what you need.
Now, for the fix() function in particular, note this hint in its manual page:
‘fix’ invokes ‘edit’ on ‘x’ and then assigns the new (edited)
version of ‘x’ in the user's workspace.
So if the change "vanishes", maybe you were editing an object which is not yours. Start with something simple, edit it and see if that persists. Along the lines of
R> hw <- function() cat("Hello, world\n")
R> fix(hw) ## editing, adding 'new'
R> hw()
Hello, new world
R>

Related

How can I add a breakpoint to debug my R package without recompiling

When I develop a R package I endup doing the following thing:
load the latest build
use it
realize there is a bug in say function 'f_bug'
try to debug
I would be easy if I could just 're-source' f_bug and that the newly sourced version would be chosen (I'd rebuild the package clean latter).
But I cannot do that, it looks like the package::f_bug is always "chosen" by default when called within another package function.
Can I do such a thing ?
You can't use RStudio's convenient graphical breakpoints, but you can do the same thing using trace:
trace(package::f_bug, browser, at = insertion_point)
Here insertion_point refers not to line numbers but to a vector of substeps. From ?trace:
look at ‘as.list(body(f))’ to get the numbers
associated with the steps in function ‘f’.)
Another option might be to use utils::setBreakpoint which takes a file name and line number as arguments. See the help file for details.

how to use utils::globalVariables

Following your recommendations (or trying to do it, at least), I have tried some options, but the problem remains, so there must be something I am missing.
I have included a more complete code
setwd("C:/naapp")
#' #import utils
#' #import devtools
I have tried with and without using suppressForeignCheck
if(getRversion() >= "2.15.1"){
utils::globalVariables(c("eleven"))
utils::suppressForeignCheck(c("eleven"))
}
myFunctionSum <- function(X){print(X+eleven)}
myFunctionMul <- function(X){print(X*eleven)}
myFunction11 <- function(X){
assign("eleven",11,envir=environment(myFunctionMul))
}
maybe I should use a particular environment?
package.skeleton(name = "myPack11", list=ls(),
path = "C:/naapp", force = TRUE,
code_files = character())
I remove the "man" directory from the directory myPack11,
otherwise I would get an error because the help files are empty.
I add the imports utils, and devtools to the descrption
Then I run check
devtools::check("myPack11")
And I still get this note
#checking R code for possible problems ... NOTE
#myFunctionMul: no visible binding for global variable 'eleven'
#myFunctionSum: no visible binding for global variable 'eleven'
#Undefined global functions or variables:eleven
I have tried also to make an enviroment, combining Tomas Kalibera's suggetion and an example I found in the Internet.
myEnvir <- new.env()
myEnvir$eleven <- 11
etc
In this case, I get the same note, but with "myEnvir", instead of "eleven"
First version of the question
I trying to use "globalVariables" from the package utils. I am building an interface in R and I am planning to submit to CRAN. This is my first time, so, sorry if the question is very basic.I have read the help and I have tried to find examples, but I still don't know how to use it.
I have made a little silly example to ilustrate my question, which is:
Where do I have to place this line exactly?:
if(getRversion() >= "2.15.1"){utils::globalVariables("eleven")}
My example has three functions. myFunction11 creates the global variable "eleven" and the other two functions manipulate it. In my real code, I cannot use arguments in the functions that are called by means of a button. Consider that this is just a silly example to learn how to use globalVariables (to avoid binding notes).
myFunction11 <- function(){
assign("eleven",11,envir=environment(myFunctionSum))
}
myFunctionSum <- function(X){
print(X+eleven)
}
myFunctionMul <- function(X){
print(X*eleven)
}
Thank you in advance
I thought that the file globals.R would be automatically generated when using globalsVariables. The problem was that I needed to create the package skeleton, then create the file globals.R, add it to the R directory in the package and check the package.
So, I needed to place this in a different file:
#' #import utils
utils::globalVariables(c("eleven"))
and save it
The documentation clearly says:
## In the same source file (to remind you that you did it) add:
if(getRversion() >= "2.15.1") utils::globalVariables(c(".obj1", "obj2"))
so put it in the same source file as your functions. It can go in any of your R source files, but the comment above recommends you put it close to your code. Looking at a bunch of github packages reveals another common pattern is to have a globals.R function with it in, but this is probably a bad idea. If you later remove the global from your package but neglect to update globals.R you could mask a problem. Putting it right close to the functions that use it will hopefully remind you when you edit those functions.
Make sure you put it outside any function definitions in the file, or it won't get seen.
You cannot modify bindings in a package namespace once the package is loaded (and namespace sealed, and bindings locked). The check tool helps you to spot violations of this restriction, so you find out about the problem when checking the package rather than while running it. globalVariables is just a call to silence check when looking for these violations, which is undesirable in almost all cases. If you really need mutable state in a package, you can create a new environment (using new.env) and bind it to an (unexported) "global" variable in your namespace. This binding will be locked, but this is ok, because in R you can change an environment in place (add/remove elements, effectively modifying the elements).
The best situation is however when you can keep all mutable state in user objects (passed in as arguments into functions, and their modified versions returned as output values of functions).

Shortcut for running a single line of code in R

Does anyone know how I could create a keyboard shortcut or something similar to run a single line of diagnostic code in R Studio? i.e. if I wanted to do something simple, like checking the dimensions of a data frame, but I wanted to do it a lot throughout the day and didn't want to be continually typing dim(data), how could I get dim(data) into a keyboard shortcut or some other quick easy way to call that single line of code?
R itself can’d do that. Your editor may be able to, though (I know that Vim + Vim-R can do something like this).
What you can do in R is bind a function to an active binding. That way, whenever you invoke the binding, it executes your piece of code. To illustrate:
makeActiveBinding('x', function () dim(data), globalenv())
Now whenever you enter x in the R console, it executes dim(data).
The plain R terminal has a reverse incremental search function to make repetitive things easy. Hit Ctrl-R and start typing, it will match against your history. In this example, I've typed "di" and its enough to find the last "dim" call I did:
> x=matrix(1:12,3,4)
> dim(x)
[1] 3 4
> y=runif(100)
> dim(x)
[1] 3 4
# hit Ctrl-R at the prompt and type "d"... "i"....
(reverse-i-search)`di': dim(x)
I can hit return now, and it will do dim(x) for me. In fact it found it at the "d" because there was nothing else starting with a "d!" in the history.
There's a similar things in Emacs-ESS but I don't suppose you are using that. I don't know if this is implemented in RStudio, StatET, Architect, RCmdr or any of the other R interfaces that you might be using. I think RStudio might have a quick history search.
You could try using the snippet feature in RStudio (Tools -> Global Options... brings up the menu below). You can then add a snippet such as the code chunk below.
snippet d
dim(data)
Once the snippet is saved you can type the d (or whatever other string you defined after snippet). Then press tab and RStudio will give you the option to replace the shortcut string with the code listed in the snippet (here dim(data)).
There might be other options but for something as simple as a dim statement. There would likely be more effort than value add.

Starting R and calling a script from a batch file

I have an R-based GUI that allows some non-technical users access to a stats model. As it stands, the users have to first load R and then type loadGui() at the command line.
While this isn't overly challenging, I don't like having to make non-technical people type anything at a command line. I had the idea of writing a .bat file (users are all running Windows, though multi-platform solutions also appreciated) that starts R GUI, then autoruns that command.
My first problem is opening RGui from the command line. While I can provide an explicit path, such as
"%ProgramW6432%\R\R-2.15.1\bin\i386\Rgui.exe"
it will need updating each time R is upgraded. It would be better to retrieve the location of RGui from the %path% environment variable, but I don't know an easy way to parse that.
The second, larger problem is how to call commands for R on startup from the command line. My first thought is that I could take a copy of ~/.Rprofile, append the extra command, and then replace the original copy of the file once R is loaded. This is awfully messy though, so I'd like an alternative.
Running R in batch mode isn't an option, firstly since I can't persuade GUIs to display themselves, and secondly because I would like the R console available, even if the users shouldn't need to use it.
If you want a toy GUI to test your ideas, try this:
loadGui <- function()
{
library(gWidgetstclck)
win <- gwindow("test")
rad <- gradio(letters[1:3], cont = win)
}
Problem 1: I simply do not ever install in the suggested default directory on Windows, but rather group R and a few related things in, say, c:/opt/ where I install R itself in, say,c:/opt/R-current so that the path c:/opt/R-current/bin will remain constant. On upgrade, I first renamed to R-previous and then install into a new R-current.
Problem 2: I think I solved that many moons ago with scripts. You can now use Rscript.exe to launch these, and there are tcltk examples for waiting for a prompt.
I have done similar a couple of times. In my cases the client was using windows so I just installed R on their computer and created a shortcut on their desktop to run R. Then I right click on the shortcut and choose properties to get the propertiest dialog. I then changed the "Start in" folder to the one where I wanted it to run from (which had the .Rdata file with the correct data and either a .First function in the .Rdata file or .Rprofile in the folder). There is also a "Run:" option that has a "Minimized" option to run the main R window minimized.
I had created the functions that I wanted to run (usually a specialized gui using tcltk) and any needed data and saved them in the .Rdata file and also either created .First or .Rprofile to run the comnand that showed the gui. The user double clicks on the icon on the desktop and up pops my GUI that they can work with while ignoring the other parts.
Take a look at the ProjectTemplate library. It does what you want to do. It loads used libraries from a batch file an run R files automatically after loading as well as a lot of other usefull stuff as well...
Using the answer from https://stackoverflow.com/a/27350487/41338 and a comment from Richie Cotton above I have arrived at the following solution to keeping a script alive until a window is closed by checking if the pointer to the window is valid.
For a RGtk2 window created and shown using:
library(RGtk2)
mainWindow <- gtkWindow("toplevel", show = TRUE)
Create a function which checks if the pointer to it exists:
isnull <- function(pointer){
a <- attributes(pointer)
attributes(pointer) <- NULL
out <- identical(pointer, new("externalptr"))
attributes(pointer) <- a
return(out)
}
and at the end of your script:
while(!isnull(mainWindow)) Sys.sleep(1)

Edit function in R and save changes (matlab-style)?

I have some R files containing functions I wrote. I source those files to have the functions available. If foo is my function and I type:
foo <- edit(foo)
or
fix(foo)
I can change the function and save it just for this session. How can I do the changes permanent, i.e. that they are saved in the source file? So far I am searching for the source file, edit it and then resource it, which can be annoying sometimes. I've seen it in Matlab, that "edit(function)" saves the changes in the source-file of the function.
thanks
I think it depends on what GUI (and hence what OS) you're running R in. Personally, I'm happy with R.app in OSX, but there are R-plugins for many common editors such as TextWrangler or Scite. IIRC these plugins allow you to execute "source" command from the editor so that saving your edits will also update the version of the function in your R-console environment.
Will saving the function object work for you? If so, use save() on the edited function and load() to load it back it. edit() and fix() are working with the parsed R objects, not the original files so it will be difficult or a pain to deparse them again
> foo <- function(x) 1:10
> writeLines("foo.txt", foo)
> writeLines(deparse(foo), "foo.txt")
> readLines("foo.txt")
[1] "function (x) " "1:10" ## not what is wanted
As #CarlWitthoft says, you might be better off using one of the many GUI and IDEs available for R. RStudio is very popular and user-friendly and Emacs + ESS is hard to beat.

Resources