Are there downsides with docstrings in R? - r

I do not like the automatic indentation of comments in
ESS (Emacs Speaks Statistics) mode, because it is so far to the right.
normalize <- function(values){
# comment
return(2* values / (max(values) - min(values)) )
}
Python uses also docstrings for comments. And I play around with it in R.
normalize <- function(values){
"comment
line 2 of comment"
return(2* values / (max(values) - min(values)) )
}
I am sure I could fix the ESS indentation of comments too, but I like the idea of multiline
comments. Are there any downsides with docstrings in GNU R?

Comments that begin with ## instead of # will be auto-indented in line with the current level of indentation.
j <- function(x) {
# One hash auto-indents to column 40
## Two hashes auto-indent to current level
### Three hashes auto-indent to BOL
rnorm(x)
}

Related

Function with two arguments in R

I am trying to better understand functions and found an example online but can't get it to work.
I want to solve an equation a, and have two arguments v and r. v= 10 and r=3. Here is my code. What am I missing? Thanks for your insights.
solve <- function(r=3,v=10) {
a <- pi*r*(sqrt(r^2+(9*v^2)/pi^2*r^4))
}
return(a)
Based on inputs. Here is the updated code. But looks like the result is not accurate.
solve <- function(r,v){
a <- pi*r*(sqrt(r^2+(9*v^2)/pi^2*r^4))
return(a)
}
solve(3,10)
R is giving me a result of 810.4933. But the example says the result is 29.9906.
Here is the formula for A:
enter image description here
You need to know the order of operations within math expressions. If you read ?Ops (kind of obscure, granted), you'll see
2. Group '"Ops"':
• '"+"', '"-"', '"*"', '"/"', '"^"', '"%%"', '"%/%"'
• '"&"', '"|"', '"!"'
• '"=="', '"!="', '"<"', '"<="', '">="', '">"'
Which suggests that * and / are consecutive. Unfortunately, your denominator of
... / pi^2*r^4
is being interpreted as
(... / pi^2) * (r^4)
which brings r^4 into the numerator.
Add parens to enforce the order of operations.
.../(pi^2*r^4)

\Sexpr{} special LaTeX characters ($, &, %, # etc.) in .Rnw-file

It has something to do with the default inline hook, I realize that and I have tried getting at it (the hook) and also read this thread and Yihui's page about hooks, but I haven't been able to solve my issue. I even tried this suggestion from Sacha Epskamp, but it didn't do this trick in my case.
I'm using \Sexpr and doing something along the lines of \Sexpr{load("meta.data.saved"); meta.data[1,7]} to print a keyword in my report, the problem is that people writing these keywords (people I can't control) are using special LaTeX characters ($, &, %, # etc.) and when they are passed to my .tex file without an \ I'm having a bad time.
I have an .Rnw file with this code,
\documentclass{article}
\begin{document}
Look \Sexpr{foo <- "me&you"; foo} at this.
\end{document}
Thsi creates an .tex file with an illegal LaTeX character. Like this,
<!-- Preamble omitted for this example. -->
\begin{document}
Look me&you at this.
\end{document}
I'm interested to get an output that looks like this,
<!-- Preamble omitted for this example. -->
\begin{document}
Look me\&you at this.
\end{document}
Sorry for the simple question, but can someone help me, and maybe others, getting starting on how to modify the default inline hook for \Sexpr?
The solution provided by #agstudy has shown the basic idea, and here is a more robust version:
hook_inline = knit_hooks$get('inline')
knit_hooks$set(inline = function(x) {
if (is.character(x)) x = knitr:::escape_latex(x)
hook_inline(x)
})
It only modifies the default inline hook when the inline result is character (otherwise just use the default hook). I have an internal function escape_latex() which hopefully escapes all special LaTeX characters correctly.
Hooking works in this case. I customize it like this :
inline_hook <- function(x) {
x <- gsub("\\&", "\\\\&", x)
x <- gsub("\\$", "\\\\$", x)
## good luck for all Latex special character
## $ % _ { } & ~ ^ < > | \
}
knit_hooks$set(inline = inline_hook)
Then
knit(input='report.Rnw')
Will reproduce your report.tex.
PS: I think it is better to not to allow users do what they want.

rstudio code folding like in matlab GUI

I normally use matlab GUI for programming and it has very nice code folding features, such as the following:
%% This is one chunk of code I can fold just because I am using the %% comment format.
matrix = [1 2 3; 4 5 6];
vector = [1 2];
ax = vector*matrix;
%% This is another chunk of code I can fold because I am using the %% comment format.
matrix2 = [7 8 9; 10 11 12];
vector2 = [7 8];
ax2 = vector2*matrix2;
As mentioned in the matlab code, the %% comment will immediatly give the matlab GUI the folding option and a plus/minus sign for unfolding/folding will appear on that line with the comment visible.
Is it anyway to achieve such formatting in rstudio or a good R gui?
I'd like to have the plus/minus feature, and the fact that the first line comment is visible so I can know what's in the folded chunk of code.
Thanks.
Photos of the GUI minus/plus unfolded/folded attached bellow:
When I try the same approach in RStudio, seems that the only option is edit -> folding collapse/expand but it hides the comments, and its not as automatable as the %% feature. In my case is more of a problem because I use X11 so I do not want to have to go to edit -> folding... all the time, but rather automate as in matlab using %%.
Have you seen the code folding section of the RStudio documentation? Everything you ask for is described therein.
To directly quote the most relevant section of the documentation, you can create a code section on any comment line by including at least four trailing dashes (-), equal signs (=), or pound signs (#) automatically creates a code section.
If that wasn't clear enough, maybe we can learn by example:
# Section One ---------------------------------
# Section Two =================================
### Section Three #############################
To illustrate that this actually works further, please examine the following two screenshots. If you are getting something different, I suggest you update RStudio and then follow up directly with the good folks at RStudio:
Expanded:
Collapsed:

Retrieving Variable Declaration

How can I find how did I first declare a certain variable when I am a few hundred
lines down from where I first declared it. For example, I have declared the following:
a <- c(vectorA,vectorB,vectorC)
and now I want to see how I declared it. How can I do that?
Thanks.
You could try using the history command:
history(pattern = "a <-")
to try to find lines in your history where you assigned something to the variable a. I think this matches exactly, though, so you may have to watch out for spaces.
Indeed, if you type history at the command line, it doesn't appear to be doing anything fancier than saving the current history in a tempfile, loading it back in using readLines and then searching it using grep. It ought to be fairly simple to modify that function to include more functionality...for example, this modification will cause it to return the matching lines so you can store it in a variable:
myHistory <- function (max.show = 25, reverse = FALSE, pattern, ...)
{
file1 <- tempfile("Rrawhist")
savehistory(file1)
rawhist <- readLines(file1)
unlink(file1)
if (!missing(pattern))
rawhist <- unique(grep(pattern, rawhist, value = TRUE,
...))
nlines <- length(rawhist)
if (nlines) {
inds <- max(1, nlines - max.show):nlines
if (reverse)
inds <- rev(inds)
}
else inds <- integer()
#file2 <- tempfile("hist")
#writeLines(rawhist[inds], file2)
#file.show(file2, title = "R History", delete.file = TRUE)
rawhist[inds]
}
I will assume you're using the default R console. If you're on Windows, you can File -> Save history and open the file in your fav text browser, or you can use function savehistory() (see help(savehistory)).
What you need to do is get a (good) IDE, or at least a decent text editor. You will benevit from code folding, syntax coloring and much more. There's a plethora of choices, from Tinn-R, VIM, ESS, Eclipse+StatET, RStudio or RevolutionR among others.
You can run grep 'a<-' .Rhistory from terminal (assuming that you've cdd to your working directory). ESS has several very useful history-searching functions, like (comint-history-isearch-backward-regexp) - binded to M-r by default.
For further info, consult ESS manual: http://ess.r-project.org/Manual/ess.html
When you define a function, R stores the source code of the function (preserving formatting and comments) in an attribute named "source". When you type the name of the function, you will get this content printed.
But it doesn't do this with variables. You can deparse a variable, which generates an expression that will produce the variable's value but this doesn't need to be the original expression. For example when you have b <- c(17, 5, 21), deparse(b) will produce the string "c(17, 5, 21)".
In your example, however, the result wouldn't be "c(vectorA,vectorB,vectorC)", it would be an expression that produces the combined result of your three vectors.

Multiline Comment Workarounds?

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

Resources