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.
Related
I happen to have a data set like this,
options(pillar.sigfig = 5)
a <- c(1.012,1,0,2.987,4)
b <- c(4.897,5,98,8.001,2.456)
tibble(A=a,
B=b) -> tibble1
and the output looks like this:
I would like to have the decimal points for the whole number shown, I tried the signif function, but it could not get the decimal values for the whole table, but I got for each column (I want it to be reflected in the whole table though :P).
Expected Output, FYR:
Decimals are not a property of the object, they are a property of the print method used on the object. For better or worse the tibble and pillar packages are very restrictive about how decimals get printed.
If you need to use tbl/tbl_df for other features, but don't like the print method, use a different print method.
Either:
print.data.frame(tibble1)
Or use this approach, which the maintainers of pillar actually recommend:
print.tbl_df <- function(x, ...) {
print.data.frame(x, ...)
invisible(x)
}
tibble1
The f_num function from the numform package will remove leading zeros from a number:
f_num(0.1)
Output:
.1
I need this very same thing, but with a comma instad of the period. It would also be great if the functionality of the f_num function which allows you to round up the number of decimals would be kept.
Here is a custom alternative(see note below):
detrail <- function(num,round_dec=NULL){
if(!is.null(round_dec)){
num<-round(num,round_dec)
}
gsub("^\\d\\.",",",num)
}
detrail(0.1)
[1] ",1"
detrail(1.1)
[1] ",1"
detrail(0.276,2)
[1] ",28"
NOTE:
To read this as numeric, you'll need to change options(OutDec) to , instead of . ie options(OutDec= ","). I have not done this as I do not like changing global options.See Also
This also removes any number that is not zero. Disable this by using 0 instead of \\d.
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.
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)
```
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)*")") )