How to add a space to an object name in R - 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.

Related

Rename a column with R

I'm trying to rename a specific column in my R script using the colnames function but with no sucess so far.
I'm kinda new around programming so it may be something simple to solve.
Basically, I'm trying to rename a column called Reviewer Overall Notes and name it Nota Final in a data frame called notas with the codes:
colnames(notas$`Reviewer Overall Notes`) <- `Nota Final`
and it returns to me:
> colnames(notas$`Reviewer Overall Notes`) <- `Nota Final`
Error: object 'Nota Final' not found
I also found in [this post][1] a code that goes:
colnames(notas) [13] <- `Nota Final`
But it also return the same message.
What I'm doing wrong?
Ps:. Sorry for any misspeling, English is not my primary language.
You probably want
colnames(notas)[colnames(notas) == "Reviewer Overall Notes"] <- "Nota Final"
(#Whatif's answer shows how you can do this with the numeric index, but probably better practice to do it this way; working with strings rather than column indices makes your code both easier to read [you can see what you're renaming] and more robust [in case the order of columns changes in the future])
Alternatively,
notas <- notas %>% dplyr::rename(`Nota Final` = `Reviewer Overall Notes`)
Here you do use back-ticks, because tidyverse (of which dplyr is a part) prefers its arguments to be passed as symbols rather than strings.
Why using backtick? Use the normal quotation mark.
colnames(notas)[13] <- 'Nota Final'
This seems to matter:
df <- data.frame(a = 1:4)
colnames(df)[1] <- `b`
Error: object 'b' not found
You should not use single or double quotes in naming:
I have learned that we should not use space in names. If there are spaces in names (it works and is called a non-syntactic name: And according to Wickham Hadley's description in Advanced R book this is due to historical reasons:
"You can also create non-syntactic bindings using single or double quotes (e.g. "_abc" <- 1) instead of backticks, but you shouldn’t, because you’ll have to use a different syntax to retrieve the values. The ability to use strings on the left hand side of the assignment arrow is an historical artefact, used before R supported backticks."
To get an overview what syntactic names are use ?make.names:
make.names("Nota Final")
[1] "Nota.Final"

Using "expression" to create list of labels with some italics, using values from a dataframe

I'm trying to create a list of labels that contain italics. I can do it with "expression" like this, and when I put them on a plot (by adding a legend as an example, but I'll use them different ways), it all works nicely.
sp.names=c(expression(paste("species ",italic("one")," sp.")),
expression(paste("species ",italic("two")," sp.")))
plot(1:10)
legend("topleft",legend=sp.names)
But instead of specifying the words in the label directly in the code, I want to call them from cells in a dataframe (because there are a lot of them and they change depending on my underlying data). But when I try and specify which dataframe cell I want, it doesn't print the labels correctly (see below). Perhaps there is a different way for me to call the cell that I want that the "expression" function will recognise?
df=data.frame(V1=c("species","species","species"),V2=c("one","two","three"))
sp.names=c(expression(paste(df$V1[1],italic(df$V2[1])," sp.")),
expression(paste(df$V1[2],italic(df$V2[2])," sp.")))
plot(1:10)
legend("topleft",legend=sp.names)
Use substitute, it substitutes variables in expressions.
sp.names=c(substitute(V1 ~ italic(V2) ~ "sp.", df[1,]),
substitute(V1 ~ italic(V2) ~ "sp.", df[2,]))
I also removed the unneeded paste (which has a different meaning within plotmath) and replaced it with ~ for increased readability.
Give bquote a shot.
sp.names <- c(bquote(.(df$V1[1])~italic(.(df$V2[1]))~" sp."),
bquote(.(df$V1[2])~italic(.(df$V2[2]))~" sp."))
plot(1:10)
legend("topleft", legend=sp.names)

Extract function argument description from R package

I know there are ways to extract all arguments to a function using, for example, rlang::fn_fmls. But is it possible to extract the description of one of these arguments from the package documentation?
For example, what if I wanted to extract the description of the na.rm argument to base::sum()?
I'm imagining something like:
get_argument_description(fn = 'base::sum', arg = 'na.rm')
Return:
"logical. Should missing values (including NaN) be removed?"
You could try to read the associated help file for that function, and grep the line where \item{argument}. However, multi-line help texts are allowed, if the next line does not start with a \ you would want to grab that too.
This answer shows a way to acess the file, then it is just a matter of grabbing the correct line(s). I also want to highlight a different function in tools,
tools:::.Rd_get_text()
Which almost gets you where you want, (if you find the correct line)
library(tools)
db = Rd_db("base")
tools:::.Rd_get_text(x = db[["sum.Rd"]])[21] # 21 is the line you want here
[1] " na.rm: logical. Should missing values (including 'NaN') be removed?"

Two PASTE functions in a character vector

attach.files = c(paste("/users/joesmith/nosection_", currentDate,".csv",sep=""),
paste("/users/joesmith/withsection_", currentDate,".csv",sep=""))
Basically, if I did it like
c("nosection_051418.csv", "withsection_051418.csv")
And I did that manually it would work fine but since I'm automating this to run every day I can't do that.
I'm trying to attach files in an automated email but when I structure it like this, it doesn't work. How can I recreate this so that the character vector accepts it?
I thought your example implied the need for "parallel" inputs to the path stem, the first portion of the file name, and the date portions of those full paths. Consider this illustration of using a 2 item vector and a one item vector (produced by Sys.Date, replacing your "currentdate") to populate the %s positions in that sprintf string (suggested by #Gregor):
sprintf("/users/joesmith/%s_%s.csv", c("nosection", "withsection"), Sys.Date() )
[1] "/users/joesmith/nosection_2018-05-14.csv" "/users/joesmith/withsection_2018-05-14.csv"

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)*")") )

Resources