knitr displaying digits of an integer without scientific notation - r

when displaying a number with inline-code with more than four digits like
`r 21645`
the result in a knitted html-file is this: 2.164510^{4} (in reality inside the inline-hook there is a calculation going on which results in 21645). Even though I just want it to print the number, like so: 21645. I can easily fix this for one instance wrapping it inside as.integer or format or print, but how do I set an option for the whole knitr-document so that it prints whole integers as such (all I need is to print 5 digits)? Doing this by hand gets very annoying. Setting options(digits = 7) doesnt help. I am guessing I would have to set some chunk-optionor define a hook, but I have no idea how

I already solved it, just including the following line of code inside the setoptions-chunk in the beginning of a knitr document:
options(scipen=999)
resolves the issue, like one can read inside this answer from #Paul Hiemstra:
https://stackoverflow.com/a/25947542/4061993
from the documentation of ?options:
scipen: integer. A penalty to be applied when deciding to print
numeric values in fixed or exponential notation. Positive values bias
towards fixed and negative towards scientific notation: fixed notation
will be preferred unless it is more than scipen digits wider.

If you don't want to display scientific notation in this instance, but also don't want to disable it completely for your knitr report, you can use format() and set scientific=FALSE:
`r format(21645, scientific=FALSE)`

Note that if you type your numeric as integer it will be well formatted:
`r 21645L`
Of course you can always set an inline hook for more flexibility( even it is better to set globally options as in your answer):
```{r}
inline_hook <- function(x) {
if (is.numeric(x)) {
format(x, digits = 2)
} else x
}
knitr::knit_hooks$set(inline = inline_hook)
```

Related

knitr: precede positive numbers with plus sign

I use knitr to have LaTeX pull numbers directly from R output, e.g., using \Sexpr{res$a[1]} to \Sexpr{res$a[5]}. Is there a way to automatically precede positive numbers with a plus sign? Sure, I could add plus signs to relevant numbers manually, but this seems to defeat the purpose of knitr.
Sorry it took me a while to get back to this. And it turned out to be easier than I thought. knitr doesn't appear to have its own options for controlling printing options. Instead, it relies on the options from your R session.
Now consider the following:
x <- 5.1234567899876543
x
[1] 5.123457
options()$digits
[1] 7
So the way the number is printed to the console is (partially) determined by options("digits"). Now, watch what happens when we apply the format function to x with all of the default arguments:
format(x)
[1] "5.123457"
We get back a character string that matches the representation when we simply printed x. Let's leverage this to our benefit:
with_plus <- function(x, ...)
{
if (x > 0)
{
sprintf(
fmt = "+ %s",
format(x, ...)
)
}
else
{
x
}
}
with_plus(x)
[1] "+ 5.123457"
Now you have a function that, under the default settings, will print numbers the same way they appear in the console but with a "+" prepended to positive numbers. Using format, you also get the flexibility to adjust individual values as needed.

How to add a space to an object name in R

Piston_Rings<-diameter[1:25,]
I want my quality control graph NOT to have the underscore in the object name.
At the moment there is an underscore (not a hyphen) in that object name. It is possible to construct objects whose names have spaces in them but in order to access them you will then always need to use backticks in order to get the interpreter to understand what you want:
> `Piston Rings` <- list(1,2)
> `Piston Rings`[[1]]
[1] 1
> `Piston Rings`[[2]]
[1] 2
The problem you incur is cluttering up your code, at least relative to obeying the usual conventions in R where a space is a token-ending marker to the parser. Hyphens (at least short-hyphens) are actually minus signs.
If on the other hand you only want to use a modified version of a name that contains an underscore as the title for a graph, then try something like this:
Piston_Rings <- list() # just for testing purposes so there will be an object.
plot( 1:10,10:1, main = sub("_", " ", quote(Piston_Rings)) )
#BondedDust's answer is correct, but (guessing, since you haven't been very specific) a simpler way to get what you want is just to specify xlab or ylab arguments to the plot() function. Let's say you have variables stuff (x) and Piston_Rings (y). If you just
plot(stuff,Piston_Rings)
then the plot will have "Piston_Rings" as the y-axis label. But if you
plot(stuff,Piston_Rings,ylab="Piston Rings")
you'll get the label you want. You can also include lots more information this way:
plot(stuff,Piston_Rings,
xlab="Important stuff (really)",
ylab="Piston Rings (number per segment)")
See ?plot.default for many more options.

How to display greater than or equal to sign using unicode \u2265

This is a follow up question to "Displaying a greater than or equal sign"
This is the text I wish to display as the y axis label:
Pr(Number of Invasions, X ≥ x)
This is the code:
expression(paste("Pr(Number of Invasions, ", italic('X'), "\u2265", italic('x'), ")"))
What I get is:
Pr(Number of Invasions, X = x)
This is the same result in the thread mentioned above. "\u2265" is supposed to overcome the issue, as suggested in the answers to the thread but it doesn't in my case.
When I run "\u2265" the result is:
"\u2265"
[1] "≥"
When I assign this to an object I get the same result:
symbol<-"\u2265"
symbol
[1] "≥"
However, in the Global Environment the object "symbol" contains "=".
Can anyone suggest how to display the symbol in the plot?
The answer isn't obvious to me.
I'm using RStudio, and OS system is Windows 7
By placing quotations marks around >= or \u2265 within paste within expression, it is was not able to produce the right symbol.
Even though I was formatting the Xs in italics, I should have just treated the code as if it was X>=x, which is what expression really wants to see, as MrFlick suggested... which makes sense now.
So:
expression(paste("Pr(Number of Invasions", italic('X')>=italic('x'), ")"))
Thanks MrFick!
You don't need paste. It's often clearer to use ~ and * as separators
plot(1,1, xlab=expression(Pr*'('*Number~of~Invasions~~ italic(X)*'\u2265'*italic(x)*")") )
That way it's easier to transition to the "full" plotmath version which gets a different spacing and looks better:
plot(1,1,
xlab=expression( Pr*'('*Number~of~Invasions~~ italic(X) >= italic(x)*")" )
)
If you had really wanted to have a named token hold the "≥" character, you can use the bquote and .( )-functions. The names inside the .( ) get evaluated (when the dot-function is within bquote):
symbol<-"\u2265"
plot(1,1,xlab=bquote(Pr*'('*Number~of~Invasions~~ italic(X) * .(symbol) * italic(x)*")") )

Force R not to use exponential notation (e.g. e+10)?

Can I force R to use regular numbers instead of using the e+10-like notation? I have:
1.810032e+09
# and
4
within the same vector and want to see:
1810032000
# and
4
I am creating output for an old fashioned program and I have to write a text file using cat.
That works fine so far but I simply can't use the e+10 notation there.
This is a bit of a grey area. You need to recall that R will always invoke a print method, and these print methods listen to some options. Including 'scipen' -- a penalty for scientific display. From help(options):
‘scipen’: integer. A penalty to be applied when deciding to print
numeric values in fixed or exponential notation. Positive
values bias towards fixed and negative towards scientific
notation: fixed notation will be preferred unless it is more
than ‘scipen’ digits wider.
Example:
R> ran2 <- c(1.810032e+09, 4)
R> options("scipen"=-100, "digits"=4)
R> ran2
[1] 1.81e+09 4.00e+00
R> options("scipen"=100, "digits"=4)
R> ran2
[1] 1810032000 4
That said, I still find it fudgeworthy. The most direct way is to use sprintf() with explicit width e.g. sprintf("%.5f", ran2).
It can be achieved by disabling scientific notation in R.
options(scipen = 999)
My favorite answer:
format(1810032000, scientific = FALSE)
# [1] "1810032000"
This gives what you want without having to muck about in R settings.
Note that it returns a character string rather than a number object
Put options(scipen = 999) in your .Rprofile file so it gets auto-executed by default. (Do not rely on doing it manually.)
(This is saying something different to other answers: how?
This keeps things sane when you thunk between multiple projects, multiple languages on a daily or monthly basis. Remembering to type in your per-project settings is error-prone and not scalable. You can have a global ~/.Rprofile or per-project .Rprofile. Or both, with the latter overriding the former.
Keeping all your config in a project-wide or global .Rprofile auto-executes it. This is useful for e.g. default package loads, data.table configuration, environment etc. Again, that config can run to a page of settings, and there's zero chance you'll remember those and their syntax and type them in

Tool/script to find and modify numerical values in CSS file?

I simply want to go through and find every numerical value in a single, or batch of, CSS files and multiple times two, then save.
Any suggestions for the easiest way to do this?
Using regular expressions could solve your problem. For example, in python you could do the following:
import re
input = "#content {width:100px;height:20.5%;font-size:150.25%;margin-left:-20px;padding:2 0 -20 14.33333;}"
regex = re.compile("-?[.0-9]+")
scaled_numbers = [float(n)*2 for n in re.findall(regex, input)]
split_text = re.split(regex, input)
output = ''
for i in range(len(scaled_numbers)):
output += "%s%.2f" % (split_text[i], scaled_numbers[i])
output += split_text[-1]
This code could be reduced in length, but I've deliberately left it less compact for readability. One flaw with it is that it contracts floats to only 2 decimal places, but that can be easily changed if you really need extended decimals (change the number in "%s%.2f" to the desired number of places).
Note also that this code could change the names of CSS selectors (for example, #footer-2 would become #footer-4.00). If you wanted to avoid that, you'll need to adjust the code to ignore text outside of {...}.

Resources