this might be nastily easy to answer:
How do I execute folded coded and in particular functions, for-loops, and alike in RStudio?
I have perused the documentary pages twice. nada.
EDIT:
But that doesn't work: If I execute the assign of a function:
ff <- function(x) {x+1 return(x)}
I get this return in non-folded manner: strg+enter
ff <- function(x) {x+1
+ return(x)}
and this when I execute the folded lines by strg+enter
> return(x)}
> Error: unexpected '}' in "return(x)}"+ return(x)}
You want to add a ; between expressions:
ff <- function(x) {x+1; return(x)}
Btw, my answer has nothing to do with RStudio, it rather answers:
How do you execute multiple statements per code block enclosed by {}
when the statements are in one line?
Only an extended comment: I'm guessing there is potential German-English confusion here. In English the three "special keys" on a Windows keyboard are "control" , "alt", and "windows", whereas on a Mac keyboard they "control", option", and "command". Originally I thought you might mean 'string+enter' or 'alt+enter' but on the basis of googling "strg+enter keyboard German" I'm thinking you mean "control-enter".
After scrolling through the keyboard shortcuts in the RStudio documentation, I'm wondering if rather than 'ctrl-enter', you really want 'windows+enter', although you will still need the semicolon, if those characters are all on the same line, or whatever it might be called in German.
Related
When R is run interactively in a terminal which supports colors, it is possible to use ANSI escape sequences in order to put colors in the prompt, such as
options(prompt = "\033[0;31mThis is red\033[0m> ")
Unfortunately, something goes wrong because for long command lines, the line continuation override the prompt instead of being written in the next line.
The problem gets worse when using several colors, because somehow each escape sequence "takes up some space" in the command line, up to the point that the end of the prompt might overwrite the beginning. On my configuration this happens with for instance
options(prompt = paste("\033[0;31m With \033[0;32m multiple",
"\033[0;33m colors \033[0;34m this",
"\033[0;35m gets \033[0;36m really",
"\033[0;37m wrong! \033[0m"))
Why is it so? Is there a workaround?
PS: This rather old post seems related http://r.789695.n4.nabble.com/Xterm-escape-sequences-in-Prompt-td906375.html
update: with R version 3.6.0 and readline 8.0 (don't know which matters here), most of the above described problem disappeared, but some strange behaviors remain. Accepted answer below resolves everything.
you need to surround each «invisible» color code with special «marks»: \001 and \002:
options(prompt = "\001\033[0;31m\002This is red\001\033[0m\002> ")
for explanation see $ info readline (or this short answer).
Gábor Csárdi on the r-devel mailing list says that I cannot easily change this behavior (http://r.789695.n4.nabble.com/buggy-ANSI-escape-sequences-in-R-prompt-td4728671.html). The workaround he proposes is to use a two lines prompt, which suits me well enough.
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.
I have looked at other posts that appeared similar to this question but they have not helped me. This may be just my ignorance of R. Thus I decided to sign up and make my first post on stack-overflow.
I am running an R-script and would like the user to decide either to use one of the two following loops. The code to decide user input looks similar to the one below:
#Define the function
method.choice<-function() {
Method.to.use<-readline("Please enter 'New' for new method and'Old' for old method: ")
while(Method.to.use!="New" && Method.to.use!="Old"){ #Make sure selection is one of two inputs
cat("You have not entered a valid input, try again", "\n")
Method.to.use<-readline("Please enter 'New' for new method and 'Old' for old method: ")
cat("You have selected", Method.to.use, "\n")
}
return(Method.to.use)
}
#Run the function
method.choice()
Then below this I have the two possible choices:
if(Method.to.use=="New") {
for(i in 1:nrow(linelist)){...}
}
if(Method.to.use=="Old"){
for(i in 1:nrow(linelist)){...}
}
My issue is, and what I have read from other posts, is that whether I use "readline", "scan" or "ask", R does not wait for my input. Instead R will use the following lines as the input.
The only way I found that R would pause for input is if the code is all on the same line or if it is run line by line (instead of selecting all the code at once). See example from gtools using "ask":
silly <- function()
{
age <- ask("How old are you? ")
age <- as.numeric(age)
cat("In 10 years you will be", age+10, "years old!\n")
}
This runs with a pause:
silly(); paste("this is quite silly")
This does not wait for input:
silly()
paste("this is quite silly")
Any guidance would be appreciated to ensure I can still run my entire script and have it pause at readline without continuing. I am using R-studio and I have checked that interactive==TRUE.
The only other work-around I found is wrapping my entire script into one main function, which is not ideal for me. This may require me to use <<- to write to my environment.
Thank you in advance.
This question already has answers here:
Multiline Comment Workarounds?
(11 answers)
Closed 9 years ago.
I found this old thread (from over a year ago), which explains how come R doesn't support a multi-line comments (like /* comment */ of PHP, for example).
I am wondering if this has been resolved in the past year, or if there are other alternatives? (For example, in notepad++ with npptor, you can mark a bunch of lines and press ctrl+q to mark them all as comments, are there similar solutions for other IDE's ?)
R Studio (and Eclipse + StatET): Highlight the text and use CTRL+SHIFT+C to comment multiple lines in Windows.
For macOS, use command+SHIFT+C.
You can, if you want, use standalone strings for multi-line comments — I've always thought that prettier than if (FALSE) { } blocks. The string will get evaluated and then discarded, so as long as it's not the last line in a function nothing will happen.
"This function takes a value x, and does things and returns things that
take several lines to explain"
doEverythingOften <- function(x) {
# Non! Comment it out! We'll just do it once for now.
"if (x %in% 1:9) {
doTenEverythings()
}"
doEverythingOnce()
...
return(list(
everythingDone = TRUE,
howOftenDone = 1
))
}
The main limitation is that when you're commenting stuff out, you've got to watch your quotation marks: if you've got one kind inside, you'll have to use the other kind for the comment; and if you've got something like "strings with 'postrophes" inside that block, then there's no way this method is a good idea. But then there's still the if (FALSE) block.
The other limitation, one that both methods have, is that you can only use such blocks in places where an expression would be syntactically valid - no commenting out parts of lists, say.
Regarding what do in which IDE: I'm a Vim user, and I find
NERD Commenter an utterly excellent tool for quickly commenting or uncommenting multiple lines. Very user-friendly, very well-documented.
Lastly, at the R prompt (at least under Linux), there's the lovely Alt-Shift-# to comment the current line. Very nice to put a line 'on hold', if you're working on a one-liner and then realise you need a prep step first.
CTRL+SHIFT+C in Eclipse + StatET and Rstudio.
if(FALSE) {
...
}
precludes multiple lines from being executed. However, these lines still have to be syntactically correct, i.e., can't be comments in the proper sense. Still helpful for some cases though.
No multi-line comments in R as of version 2.12 and unlikely to change. In most environments, you can comment blocks by highlighting and toggle-comment. In emacs, this is 'M-x ;'.
Put the following into your ~/.Rprofile file:
exclude <- function(blah) {
"excluded block"
}
Now, you can exclude blocks like follows:
stuffiwant
exclude({
stuffidontwant
morestuffidontwant
})
Unfortunately, there is still no multi-line commenting in R.
If your text editor supports column-mode, then use it to add a bunch of #s at once. If you use UltraEdit, Alt+c will put you in column mode.
I (sort of) already know the answer to this question. But I figured it is one that gets asked so frequently on the R Users list, that there should be one solid good answer. To the best of my knowledge there is no multiline comment functionality in R. So, does anyone have any good workarounds?
While quite a bit of work in R usually involves interactive sessions (which casts doubt on the need for multiline comments), there are times when I've had to send scripts to colleagues and classmates, much of which involves nontrivial blocks of code. And for people coming from other languages it is a fairly natural question.
In the past I've used quotes. Since strings support linebreaks, running an R script with
"
Here's my multiline comment.
"
a <- 10
rocknroll.lm <- lm(blah blah blah)
...
works fine. Does anyone have a better solution?
You can do this easily in RStudio:
select the code and click CTR+SHIFT+C
to comment/uncomment code.
This does come up on the mailing list fairly regularly, see for example this recent thread on r-help. The consensus answer usually is the one shown above: that given that the language has no direct support, you have to either
work with an editor that has region-to-comment commands, and most advanced R editors do
use the if (FALSE) constructs suggested earlier but note that it still requires complete parsing and must hence be syntactically correct
A neat trick for RStudio I've just discovered is to use #' as this creates an self-expanding comment section (when you return to new line from such a line or insert new lines into such a section it is automatically comment).
[Update] Based on comments.
# An empty function for Comments
Comment <- function(`#Comments`) {invisible()}
#### Comments ####
Comment( `
# Put anything in here except back-ticks.
api_idea <- function() {
return TRUE
}
# Just to show api_idea isn't really there...
print( api_idea )
`)
####
#### Code. ####
foo <- function() {
print( "The above did not evaluate!")
}
foo()
[Original Answer]
Here's another way... check out the pic at the bottom. Cut and paste the code block into RStudio.
Multiline comments that make using an IDE more effective are a "Good Thing", most IDEs or simple editors don't have highlighting of text within simple commented -out blocks; though some authors have taken the time to ensure parsing within here-strings. With R we don't have multi-line comments or here-strings either, but using invisible expressions in RStudio gives all that goodness.
As long as there aren't any backticks in the section desired to be used for a multiline comments, here-strings, or non-executed comment blocks then this might be something worth-while.
#### Intro Notes & Comments ####
invisible( expression( `
{ <= put the brace here to reset the auto indenting...
Base <- function()
{ <^~~~~~~~~~~~~~~~ Use the function as a header and nesting marker for the comments
that show up in the jump-menu.
--->8---
}
External <- function()
{
If we used a function similar to:
api_idea <- function() {
some_api_example <- function( nested ) {
stopifnot( some required check here )
}
print("Cut and paste this into RStudio to see the code-chunk quick-jump structure.")
return converted object
}
#### Code. ####
^~~~~~~~~~~~~~~~~~~~~~~~~~ <= Notice that this comment section isnt in the jump menu!
Putting an apostrophe in isn't causes RStudio to parse as text
and needs to be matched prior to nested structure working again.
api_idea2 <- function() {
} # That isn't in the jump-menu, but the one below is...
api_idea3 <- function() {
}
}
# Just to show api_idea isn't really there...
print( api_idea )
}`) )
####
#### Code. ####
foo <- function() {
print( "The above did not evaluate and cause an error!")
}
foo()
## [1] "The above did not evaluate and cause an error!"
And here's the pic...
I can think of two options. The first option is to use an editor that allows to block comment and uncomment (eg. Eclipse). The second option is to use an if statement. But that will only allow you to 'comment' correct R syntax. Hence a good editor is the prefered workaround.
if(FALSE){
#everything in this case is not executed
}
If find it incredible that any language would not cater for this.
This is probably the cleanest workaround:
anything="
first comment line
second comment line
"
Apart from using the overkilled way to comment multi-line codes just by installing RStudio, you can use Notepad++ as it supports the syntax highlighting of R
(Select multi-lines) -> Edit -> Comment/Uncomment -> Toggle Block Comment
Note that you need to save the code as a .R source first (highlighted in red)
I use vim to edit the R script.
Let's say the R script is test.R, containing say "Line 1", "Line 2", and "Line 3" on 3 separate lines.
I open test.R on the command line with Vim by typing "vim test.R".
Then I go to the 1st line I want to comment out, type "Control-V", down arrow to the last line I want to comment out, type a capital I i.e. "I" for insert, type "# ", and then hit the Escape key to add "# " to every line that I selected by arrowing down. Save the file in Vim and then exit Vim by typing ":wq". Changes should show up in Rstudio.
To delete the comments in Vim, start at the first line on top of the character "#" you want to delete, again do "Control-V", and arrow down to the last line you want to delete a "#" from. Then type "dd". The "#" signs should be deleted.
There's seconds-worth of lag time between when changes to test.R in Vim are reflected in Rstudio.
Now there is a workaround, by using package ARTofR or bannerCommenter
Examples here:
In RStudio an easy way to do this is to write your comment and once you have used CTRL + Shift + C to comment your line of code, then use CTRL + SHIFT + / to reflow you comment onto multiple lines for ease of reading.
In RStudio you can use a pound sign and quote like this:
#' This is a comment
Now, every time you hit return you don't need to add the #', RStudio will automatically put that in for you.
Incidentally, for adding parameters and items that are returned, for standardization if you type an # symbol inside those comment strings, RStudio will automatically show you a list of codes associated with those comment parameters:
#' #param tracker_df Dataframe of limit names and limits
#' #param invoice_data Dataframe of invoice data
#' #return return_list List of scores for each limit and rejected invoice rows