Frost_Maggot Frost_Maggot - 3 months ago 15
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:

paste(report)

007.2


The following will produce a tailing zero:

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

7.20


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

Much thanks in advance.

Answer

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))
Comments