I'm trying to write a dashboard with shinydashboard in R to display some values using renderValueBox and valueBoxOutput. These values are not hardcoded but are being scraped from another source daily.
These values are currency numbers and should be reporting like $XXX,XXX.XX but instead I see XXXXXX.XX. Is there a way, like a wrapper, to easily format those values? Otherwise I've thought of brute forcing some regex on it with gsub...but ew. Please and thanks :)
Discovered the function prettyNum(): this function is amazing for simple conversion to comma separated numerics.
> prettyNum(56789, big.mark = ",")
> 56,789
Another way is to use the {scales} package and the dollar_format() function.
This function is a labelling function factory, in the sense that it creates other functions.
I usually need to output numbers in euros, so I defined the following function:
euro_format <- scales::dollar_format(
prefix = "\u20ac", # the euro symbol
suffix = "",
big.mark = ",",
decimal.mark = ".",
accuracy = 1
)
>euro_format(20842)
[1] "€20,842"
Related
I have built a table using the reactable package in RStudio. The first column contains text and all the others contain monetary values. I have added a footer which contains the total of each column except the first. For the body of the table, I added separators to the numbers (because they are large numbers) using
colDef(format = colFormat(prefix = "£", separators = TRUE, digits = 2)
but this does not apply to the footer and I can't find out how to get the numbers in the footer in the same format. The footer was made using
sprintf("£%.2f", sum(values))
and so has the correct prefix and decimal places, but not the separators. Does anyone know how to do this? Thank you!
You have to specify the separator in the footer function. I use the following method with the prettyNum function:
colDef(format = colFormat(prefix = "£", separators = TRUE, digits = 2), # format rest of columns
footer = function(values) prettyNum(sprintf("£%.2f", sum(values)), big.mark = ",", preserve.width = "none") # format footer
There is also the scales library, I don't use it but many others do. You might look into that as well.
After reading a csv file
data<-read.table(paste0('C:/Users/data/','30092017ARB.csv'),header=TRUE, sep=";")
I get for rather all numeric variable factor as the type, specially for the last column.
I tried all suggestion here However, I get a warning for all suggestions
Warning message:
NAs introduced by coercion
Some one mentioned even in this post:
"Every answer in this post failed to generate results for me , NAs were getting generated."
any idea how can I solve this problem?
Addendum: in the following pic you can see one possible approach suggested in here
However, I get always the same NA .
The percent sign is clearly the problem. Replace the "%" by the empty string, "", and then convert to numeric.
data[[3]] <- sub("%", "", data[[3]])
data[[3]] <- as.numeric(data[[3]])
You can do this in one line of code,
data[[3]] <- as.numeric(sub("%", "", data[[3]]))
Also, two notes on reading the data in.
First, some files use the semi-colon as a column separator. This is very used in countries where the decimal point is the comma. That is why R has two functions to read files in the CSV format.
These functions are both calls to read.table with some defaults changed.
read.csv - Sets arguments header = TRUE and sep = ",".
read.csv2 - Sets arguments header = TRUE, sep = ";" and dec = ",".
For a full explanation see read.table or at an R prompt run help("read.table").
Second, you can avoid factor problems if you use argument stringsAsFactors = FALSE from the start, when reading in the data.
How can I convert dates in R to a string without dashes or slashes or letters and times without colons. For example I can get 2017-12-07 in R but I need 201712071520 to use in an Weather API call. How can I do that? For reference please see the example call below for startDateTime and endDateTime. I would like to convert the dates that I have into 20171207 format and append it with a fixed time (1520) without the colon. Thanks for helping!
I have been told this question has been asked before but the other examples are doing the opposite converting character strings into R dates and times.
Here is an example of the API I am calling:
https://api.weather.com/v3/wx/hod/conditions/historical/point?pointType=nearest&geocode=39.86,-104.67&startDateTime=201712071520&endDateTime=201712071520&units=e&format=json&apiKey=yourApiKey
Moved from comments.
If x is of R's "Date" class then use the indicated format statement:
x <- as.Date("2017-12-07") # test input
format(x, "%Y%m%d1520")
## [1] "201712071520"
See ?strptime for more on percent codes.
This is a bit more generic solution. It would look like this:
library(lubridate)
input_date = "2017-1-7" #intentionally taking different date to make it more generic
fixed_text = "1520"
input_date = ymd(input_date)
output_date = paste(year(input_date), sprintf(fmt = '%02d', month(input_date)), sprintf(fmt = '%02d', day(input_date)), fixed_text, sep = "")
print(output_date)
I've used read.table to read a file that contains numbers such as 0.00001
when I write them back with write.table those numbers appear as 1e-5
How can I keep the old format?
I would just change the scipen option before calling write.table. Note that this will also change how numbers are displayed when printing to the console.
options(scipen=10)
write.table(foo, "foo.txt")
options(scipen=0) # restore the default
You can do this by converting your numbers to strings with formatting as you require, then using the argument quote = FALSE in the call to write.table.
dfr <- data.frame(x = 10^(0:15))
dfr$y <- format(dfr$x, scientific = FALSE)
write.table(dfr, file = "test.txt", quote = FALSE)
Note that you shouldn't need to change the format of the numbers in your file. Pretty much every piece of scientific software and every spreadsheet understands scientific notation for numbers, and also has number formatting options so you can view them how you choose.
If the input is a mixture of scientific notation and explicit notation numbers, then you will be writing your own parser to read in the numbers and keep track of which ones were in which formats. In fact, you'll want to keep a string representation of those numbers lying around so you can write back exactly what was in the input.
However, if you just want to write.table() with consistently explicit notation, try.
write.table(format(_your_table_here_, scientific=FALSE), ...)
For maximum control loop over all rows and print them to a text file formatted with sprintf
# Find number of rows in data.frame test
nrows <- dim(test)[1]
# init a new vector
mylines <- vector("character",dim(test)[1])
# loop over all rows in dataframe
for(i in 1:nrows){
# Print out exactly the format you want
mylines[i] <- sprintf("Line %d: %.2f\t%.2f",1,test[i,"x"],test[i,"y")
}
# write lines to file
writeLines(mylines,"out.txt")
I'd like to convert my csv files into xts objects as efficiently as possible. I seem to be stuck though with having to first applying the read.zoo method to create a zoo objects before being able to convert it to an xts object.
gold <- read.zoo("GOLD.CSV", sep=",", format="%m/%d/%Y", header=TRUE)
Gold <- as.xts (gold, order.by=index(gold), frequency=NULL)
Is this the most efficient way of converting my initial GOLD.CSV file into an R xts object?
If it is a file, you need to read it.
So use read.zoo() as you -- but then convert rightaway:
gold <- as.xts(read.zoo("GOLD.CSV", sep=",", format="%m/%d/%Y", header=TRUE))
Ok?
You can write your own read.xts function. We would call it a wrapper function and it should go something along the lines of
read.xts <- function(x, format = "%m/%d/%Y", header = TRUE, sep = ",") {
result <- as.xts(read.zoo(x, sep = sep, format = format, header = header))
return(result)
}
read.xts(file.choose()) # select your file
Notice the arguments in function(). They are passed to the body of the function (code between curly braces). If function() arguments have values, this means that this is their default. If you assign new values (e.g. function(x = "my.file.csv", sep = "\t")), they will overwrite the defaults. The last line shows you how you can use your new function. Feel free to extend this function with the rest of the read.zoo arguments. Should you have any specific question on how to do it, don't by shy and just ask. :)
I use a few of little gems like that in my daily work. I've created a file called workhorse.R and I load it (e.g. source("d:/workspace/workhorse.R")) whenever I need any of the little functions.