Is it possible to place code into the console in R? - r

Blasphemy I know to ask IF it is possible to do something in R, but here I am!
I am interested in the ability to create a function that will place code into the console. In other words, if the user types in f("3+3") and hits enter then the console will be waiting for the next command with > 3+3. Then when the user hits enter, it will return 6 in this case. Possible? Any ideas?
I wish I had more to share but I've never even thought this functionality would be useful before...

One way you could do this is to call system2() to invoke an external utility that synthesizes keyboard input. I've written a C++ program called sendkeys that can do this on Windows by (ultimately) calling SendInput(). Demo:
system2('sendkeys','3\\\\+3');
3+3
## [1] 6
(The backslash escaping is necessary because of the way my utility parses its input; + is a metachar that must be escaped to become literal.)
Let me know if you want my C++ code.

Would that be the kind of function you would need? Maybe it is not a very elegant solution, though.
printEval <- function(x){
cat(">", x,"\n")
cat ("Press [enter] to continue")
line <- readline()
eval(parse(text=x))
}
EDIT: Sorry, I just noticed that the eval(parse()) solution was already suggest by #Ping in the comment field right under the question.

Related

How to scroll up in Vim buffer with R (using Nvim-R)

I'm a happy user of the Nvim-R plugin, but I cannot find out how to scroll up in the buffer window that the plugin opens with R. Say for instance that I have a large output in console, but I cannot see the top of it - how do I scroll up to see this? In tmux for instance there's a copy mode that quite handily lets you do this, but how is this done in the R buffer?
An example below where I'm very curious to see what's on the line above the one begining with "is.na(a)...". How can this be achieved?
I have scoured the documentation found here, but without luck.
The answer is apparently to use Ctrl+\ Ctrl+n according to this answer on the bugreports for NVim-R.
Here's what my output looks like when I output mtcars:
When I hit Ctrl+\ Ctrl+n, I can move the cursor and I get line numbers:
To get back to interactive, I just use i, the same way I normally would.
Apparently, if you are using neovim, then you can add let R_esc_term = 0 in your ~/.vimrc file and you can then use the escape key, but if you don't use neovim, you are stuck using the two ctrl commands ¯\_(ツ)_/¯.
As pointed out by ZNK, it is about switching to normal mode in Vim's terminal. This, however, can easily fail due to cumbersome keybinding. If such is the case, remap the default keybinding to something reasonable, say, by putting this in your .vimrc:
tnoremap jk <C-\><C-n>
This works for me in Linux running Vim 8.0 in terminal (e.g. does not require Neovim). As you can see, I use 'jk' to switch from insert to normal mode. One can use Esc instead of jk, however, this makes me unable to use up arrow to retrieve command line history as been reported elsewhere.

Is there a way to let the console in RStudio produce time stamps? [duplicate]

I wonder if there is a way to display the current time in the R command line, like in MS DOS, we can use
Prompt $T $P$G
to include the time clock in every prompt line.
Something like
options(prompt=paste(format(Sys.time(), "%H:%M:%S"),"> "))
will do it, but then it is fixed at the time it was set. I'm not sure how to make it update automatically.
Chase points the right way as options("prompt"=...) can be used for this. But his solutions adds a constant time expression which is not what we want.
The documentation for the function taskCallbackManager has the rest:
R> h <- taskCallbackManager()
R> h$add(function(expr, value, ok, visible) {
+ options("prompt"=format(Sys.time(), "%H:%M:%S> "));
+ return(TRUE) },
+ name = "simpleHandler")
[1] "simpleHandler"
07:25:42> a <- 2
07:25:48>
We register a callback that gets evaluated after each command completes. That does the trick. More fancy documentation is in this document from the R developer site.
None of the other methods, which are based on callbacks, will update the prompt unless a top-level command is executed. So, pressing return in the console will not create a change. Such is the nature of R's standard callback handling.
If you install the tcltk2 package, you can set up a task scheduler that changes the option() as follows:
library(tcltk2)
tclTaskSchedule(1000, {options(prompt=paste(Sys.time(),"> "))}, id = "ticktock", redo = TRUE)
Voila, something like the MS DOS prompt.
NB: Inspiration came from this answer.
Note 1: The wait time (1000 in this case) refers to the # of milliseconds, not seconds. You might adjust it downward when sub-second resolution is somehow useful.
Here is an alternative callback solution:
updatePrompt <- function(...) {options(prompt=paste(Sys.time(),"> ")); return(TRUE)}
addTaskCallback(updatePrompt)
This works the same as Dirk's method, but the syntax is a bit simpler to me.
You can change the default character that is displayed through the options() command. You may want to try something like this:
options(prompt = paste(Sys.time(), ">"))
Check out the help page for ?options for a full list of things you can set. It is a very useful thing to know about!
Assuming this is something you want to do for every R session, consider moving that to your .Rprofile. Several other good nuggets of programming happiness can be found hither on that topic.
I don't know of a native R function for doing this, but I know R has interfaces with other languages that do have system time commands. Maybe this is an option?
Thierry mentioned system.time() and there is also proc.time() depending on what you need it for, although neither of these give you the current time.

time command running on function wont let the function print

I have a problem with my code. It doesn't print out an error, it works but it doesn't do what I actually need it to do. I won't be posting all of the code because it is not needed, I will just post the line we need.
So I have this line of code:
TIME1=$( { time awkfun ; } 2>&1 >/dev/null);
Where awkfun is a function that should print 500 integers, and TIME1 is a variable to store the time that the function will need to run and print. Problem is that normally as I said the function would print around 500 integers in this occasion though that I am using this, it just runs and does the calculations but is not printing. So it actually runs the awkfun function but doesn't let it print, in the time output for this function I also need the time it needs to print everything.
How to do that?
I hope I explained it as good as possible, if any questions arise please don't hesitate to comment, thanks in advance!
P.S
Running in ksh in oracle solaris.
Here is the correct sequence. Adjust as needed:
TIME1=`time (awkfun > /dev/tty) 2>&1`

Writing help information for user defined functions in R

I frequently use user defined functions in my code.
RStudio supports the automatic completion of code using the Tab key. I find this amazing because I always can read quickly what is supposed to go in the (...) of functions/calls.
However, my user defined functions just show the parameters, no additional info and obviously, no help page.
This isn't so much pain for me but I would like to share code I think it would be useful to have some information at hand besides the #coments in every line.
Nowadays, when I share, my lines usually look like this
myfun <- function(x1,x2,x3,...){
# This is a function for this and that
# x1 is a factor, x2 is an integer ...
# This line of code is useful for transformation of x2 by x1
some code here
# Now we do this other thing
more code
# This is where the magic happens
return (magic)
}
I think this line by line comment is great but I'd like to improve it and make some things handy just like every other function.
Not really an answer, but if you are interested in exploring this further, you should start at the rcompgen-help page (although that's not a function name) and also examine the code of:
rc.settings
Also, executing this allows you to see what the .CompletionEnv has in it for currently loaded packages:
names(rc.status())
#-----
[1] "attached_packages" "comps" "linebuffer" "start"
[5] "options" "help_topics" "isFirstArg" "fileName"
[9] "end" "token" "fguess" "settings"
And if you just look at:
rc.status()$help_topics
... you see the character items that the tab-completion mechanism uses for matching. On my machine at the moment there are 8881 items in that vector.

Tweaking the R readline behavior

The R interactive interface implements the shell-like read line behavior (I have no better words to formulate this...).
For example, pressing Ctrl-W kills the preceding word.
Now, I would like this mechanism to stop at characters other than alphanumeric. For example, if I have entered
data.frame(Ant
and press Ctrl-W, the whole string data.frame(Ant is killed. I would much prefer the Ctrl-W to kill the Ant and stop short of the left parenthesis.
Is there a way of tweaking this behavior?
The behaviour of readline depends upon the operating system and the IDE. On Windows, CRTL-W doesn't delete the previous word. I don't think that there's a trivial way of changing the behaviour. At a guess, start digging around in:
http://svn.r-project.org/R/trunk/src/library/utils/src/io.c

Resources