R print a units number with the respective unit

83 views Asked by At

I have a script using number parameters with units. When printing messages to the log/user, I want the print to add the respective unit. I expected R to be smart enough to do so when doing:

library(units)

min_size = set_units(1200, "m^2")
print(paste0("Must be at least ", min_size))

# Prints: "Must be at least 1200"
# I want: "Must be at least 1200 m^2")

# ideally without explicitly adding " m^2", to avoid code inconsistency when changing units
print(paste0("Must be at least ", min_size, " m^2"))
2

There are 2 answers

1
Honeybear On

The simple answer is to use units(min_size) to get a printable representation of the unit.

print(paste0("Must be at least ", min_size, " ", units(min_size)))
0
user2554330 On

You have a couple of workarounds: printing the units explicitly, or using format() to append them automatically.

I'll try to answer the question of why your original attempt (relying on paste0() to do the formatting) didn't work.

paste0() converts objects to character strings using as.character(). In general, as.character() isn't the method you should use for a nice display. For example, as.character(pi) gives "3.14159265358979", ignoring the user's options("digits") setting. When you want things displayed in a nice user-friendly way, use format() to do the conversion. For example, format(pi) gives "3.141593".

So why doesn't paste0() use format()? Because format() loses a lot of information when it rounds. You can't get it back from the string produced. On the other hand, as.character() loses less. (It does lose some info; as.numeric(as.character(pi)) is not equal to pi, and as.character(min_size) uses the default method, so it loses the unit information.)

I hope this helps to explain what's going on.