Frost_Maggot Frost_Maggot - 1 year ago 56
R Question

Display a leading zero AND a tailing zero in an R object imported through a SQL query

I need to produce a print statement of any type (I would prefer cat or paste for consistency with the rest of the work).

The problem I have is I can not find a way to print an object of the form XX.XX when it has a leading zero and a tailing zero, for example 07.20.

Normally this would not be a problem but the object comes from a database via a RODBC SQL query.

I can achieve a leading zero usually in the following way:

X <- paste(SQL QUERY HERE)

report <- formatC(as.vector(t(RODBC::sqlQuery(channel, X))),
width = 5, flag = "0")

however for a character with a leading and tailing zero this will print the following:



The following will produce a tailing zero:

report <- formatC(as.vector(t(RODBC::sqlQuery(channel, X))),
format = 'f', digits = 2)


Any combination of the two methods seems to just favour one and produces one of the above results.

Much thanks in advance.

Answer Source

A few examples just to fix ideas (still can't understand what you need):

## val <- as.vector(t(RODBC::sqlQuery(channel, X)))
val <- 7.2
sprintf("%05.2f", val)
val <- "007.2"
sprintf("%05.2f", as.numeric(val))