I'm trying to add a '+' symbol to show a percent increase in numbers that were made into characters in order to add a % sign in front of all of them. Here is some sample data:
###Create Data
First.Name <- c("Sharon", "Megan", "Kevin")
ProjManagment <- c(5, 7,3)
ClientManagment <- c(3,6,2)
StatProgram <- c(2,3,7)
jobForm = data.frame(First.Name, ProjManagment, ClientManagment, StatProgram)
And the code to make them into percentages:
as.character(jobForm[2:4])
jobForm[2:4] <- lapply(jobForm[2:4], function(x) paste(x, "%"))
I have tried to do this:
jobForm[32:39] <- lapply(jobForm[32:39]) function(x) if(strsplit(x[0] != "-")) {paste("+", x)}
and this from a previously posted question:
jobForm[32:39] <- lapply(jobForm[32:39], function(x, ...)
{
if (x[1] != "-")
{
sprintf(
fmt = "+ %s",
format(x, ...)
)
}
else
{
x
}
})
But none have worked. Any help would be greatly appreciated, thank you
No need for an if
/else
condition here. You can simply use sprintf
with the format specifiers "%+d"
or %+f
; e.g.
jobForm[2:4] <- lapply(jobForm[2:4], function(x) sprintf("%+3d %%", x))
# First.Name ProjManagment ClientManagment StatProgram
#1 Sharon +5 % +3 % +2 %
#2 Megan +7 % +6 % +3 %
#3 Kevin +3 % +2 % +7 %
Explanation: Let's break down the format specifier "%+3d"
: The +
flag adds a leading plus, 3
specifies three integer digits, and d
(f
) specifies an integer (float). We escape the percentage sign inside sprintf
by doubling it.
A minimal example to further demonstrate
x <- c(0.0, -3.2, 4.2)
sprintf("%+3d %%", x)
#[1] " +0 %" " -3 %" " +4 %"
sprintf("%+3.1f %%", x)
#[1] "+0.0 %" "-3.2 %" "+4.2 %"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With