How present currency value in French format in R - r

I have part of code that should show currency value in a French format
This code
library(formattable)
currency(x = 123456, symbol = "€", digits = 0)
gives me "€123,456".
I need code that gives me "123 456€" in a French format for one single value.
Thanks!

I'm not sure how to do it with currency function. It seems to not take in consideration putting the symbol after.
You can maybe use prettyNum function from base R in combination with paste to add the symbol at the end:
paste(prettyNum(x, big.mark = " ",big.interval = 3), "€")
[1] "123 456 €"
Alternatively, in DT, you can use formatCurrency function:
library(DT)
x = 123456
datatable(as.matrix(x)) %>% formatCurrency(1, '\U20AC', digits = 0, before = FALSE, mark = "")
Does it answer your question ?

Related

How to specify big marks separator in flextable object without using column names?

Context: I am creating .docx table using awesome package flextable. This package has a function to format numbers in the final output: set_formatter_type(). This function, if i understand correctly, requires a character input that can be used by sprintf(). I was able to acheive the expected output using set_formatter() but it required to explicitely name each column and I can not do that with my real table.
Problem: I can not find how to add big marks (e.g. thousand separator) using sprintf() synthax that works with flextable::set_formatter_type().
It is possible to acheive the right formatting using formatC() but this function does not work with flextable::set_formatter_type()
formatC(x = signif(1715235456.5684, 3), big.mark = " ", digits = 0, format = "f")
[1] "1 720 000 000"
Using sprintf() I was able to acheive:
sprintf("%.0f", signif(1715235456.5684, 3))
[1] "1720000000"
Reproducible example:
df <- flextable::flextable(iris[1:3]*1000)
flextable::set_formatter_type(df, fmt_double = "%.0f") # works fine but I can't get big mark separator
flextable::set_formatter_type(df, fmt_double = function(x) formatC(x, digits = 0, big.mark = " ")) # does not work (error)
flextable::set_formatter(df, Sepal.Length = function(x) formatC(x, digits = 0, big.mark = " ", format = "f")) # works but I would like not to have to name each column from my real life dataframe...
Expected output:
flextable::set_formatter(df,
Sepal.Length = function(x) formatC(x, digits = 0, big.mark = " ", format = "f"),
Sepal.Width = function(x) formatC(x, digits = 0, big.mark = " ", format = "f"),
Petal.Lenght = function(x) formatC(x, digits = 0, big.mark = " ", format = "f"))
Thanks to #TarJae and #DavidGohel comments, here is how the problem can be solved using flextable::colformat_double() function as described here: https://github.com/davidgohel/flextable/blob/master/R/formatters.R#L135
Up to date information can be found here: https://ardata-fr.github.io/flextable-book/cell-content-1.html#simple-formatting-of-cell-content
df <- flextable::flextable(iris[1:3]*1000)
flextable::colformat_double(df, big.mark = " ", digits = 0)
The output:
Credits: Formatting multiple columns with flextable r package

How to extract specific symbol from text in R

I'm setting up a new project in R ,and want to extract specific symbol from text
X <- c("amazing tiny phone ^_^","so cute!!! <3")
I would like to extract ^_^ and <3 from X in R
Thank you!
More straightforward
X = c("amazing tiny phone ^_^","so cute!!! <3","^_^ and :) are my fav symbols")
patt=c("=d" ,"<3" , ":o" , ":(" ,
":)" , "(y)" , ":*" , "^_^", ":d" ,";)" , ":'(")
variable = sapply(X,function(x){
i = which(patt%in%strsplit(x," ")[[1]])
if (length(i)>0){
paste(patt[i],collapse=" ")
} else{NA}
})
names(variable)=NULL
> variable
[1] "^_^" "<3" ":) ^_^" NA
#GraemeForst A generalization could be achieved using groupings and lookaheads:
group <- "[\\^\\_\\<\\>3\\:\\(\\)\\;]"
pat <- sprintf(".*[\\s\\b](%s+)(?!\\1)", group)
group defines the character grouping. Basically all symbols we want to extract.
pat defines our matching pattern. The [\\s\\b] says prior to a possible match there must be either a blank or the boundary. And (?!\\1) say after a match there cannot be an element of group.
Here is a demo:
X <- c("amazing tiny phone ^_^","so cute!!! <3", "I like pizza :)", "hello beautiful ;)")
gsub(pat, "\\1", grep(pat, X, value = TRUE, perl = TRUE), perl = TRUE)
# [1] "^_^" "<3" ":)" ";)"
This can be further refined and generalized. An very simple step one can add is to extend the grouping.
Old Answer
You can use regex for this:
# create the pattern to be extracted
pat = ".*(\\^\\_\\^).*|.*(\\<3).*" # escape special characters with "\\" and ".*" to specify there may be text before/after
# extract
gsub(pat, "\\1\\2", grep(pat, X, value = TRUE, perl = TRUE), perl = TRUE)
# [1] "^_^" "<3"

Move "*" to new column in R

Hello I have a column in a data.frame, it has many rows, e.g.,
df = data.frame("Species" = c("*Briza minor", "*Briza minor", "Wattle"))
I want to make a new column "Species_new" where the "*" is moved to the end of the character string, e.g.,
df = data.frame("Species" = c("*Briza minor", "*Briza minor", "Wattle"),
"Species_new" = c("Briza minor*", "Briza minor*", "Wattle"))
Is there a way to do this using gsub? The manual example would take far too long as I have approximately 50,000 rows.
Thanks in advance
One option is to capture the * as a group and in the replacement reverse the backreferences
df$Species_new <- sub("^([*])(.*)$", "\\2\\1", df$Species)
df$Species_new
#[1] "Briza minor*" "Briza minor*" "Wattle"
NOTE: * is a metacharacter meaning 0 or more, so we can either escape (\\*) or place it in brackets ([]) to evaluate the raw character i.e. literal evaluation
Thanks so much for the quick response, I also found a workaround;
df$Species_new = sub("[*]","",df$Species, perl=TRUE)
differences = setdiff(df$Species,df$Species_new)
tochange = subset(df,df$Species == differences)
toleave = subset(df,!df$Species == differences)
tochange$Species_new = paste(tochange$Species_new, "*", sep = "")
df = rbind(tochange,toleave)

using the first and last character of a string to create another variable

My data looks like this:
df <- tibble(code = c("B12345A", "B12345C"))
I want to create a second variable, say 'code_2', that takes the first and last character of the string in the first variable like this:
df <- df %>%
mutate(code_2 = str_sub(code, 1, 1),
code_3 = str_sub(code, 7, 7)) %>%
unite(code_2, 2:3, sep = "", remove = TRUE)
But surely there's a more succinct way to achieve the above using dplyr tools? (I'm thinking I could create a function to achieve this too, but I'm not sure how to go about that either.) Thanks in advance for your help.
mutate(code_2 = paste0(substr(code,1,1), substr(code,7,7)))`
Or if the length of the strings can vary:
mutate(code_2 = paste0(substr(code,1,1), substr(code,nchar(code),nchar(code))))
Change substr to str_sub if you prefer the function from the stringr package.
You could also use a regular expression:
mutate(code_2 = gsub("(.).*(.)", "\\1\\2", code))

Set up different fonts for fragments of string in R

I have a long string txt that I want to display as margin text in a plot using mtext(). The txt string is composed of another string txt.sub, as well as of a date string, which applies a specific format to a date command argument. However, I want to display the "date" part of that string only in bold.
The string is:
date.in = as.Date( commandArgs( trailingOnly=TRUE )[1], format="%m/%d/%Y" )
date = format(date.in, "%b %d, %Y")
txt.sub = "Today's date is: "
txt = paste(txt.sub, date, sep = "")
I tried the following
## Plot is called first here.
mtext(expression(paste(txt.sub, bold(date), sep = "")), line = 0, adj = 0, cex = 0.8)
but the problem with this is that it doesn't paste the values of txt.sub and date, but rather displays literally the words "txt.sub" and "date".
Is there any way to get to the result I am looking for? Thank you!
Adjusting one of the examples from the help page on mathematical annotation (see example 'How to combine "math" and numeric variables'):
mtext(bquote(.(txt.sub) ~ bold(.(date))), line=0, adj=0, cex=0.8)

Resources