How do I quickly convert the size element of file.info() from bytes to KB, MB, GB, etc.?
The object.size()
function does this type of formatting for it's results, but its meant to tell you the size of the R object you pass to it. It is not set up to take an arbitrary by value.
However, we can "steal" some of it's formatting logic. You can call it with
utils:::format.object_size(60963, "auto")
# [1] "59.5 Kb"
In that way we can call the un-exported formatting function. You can bring up the additional formatting options on the ?format.object_size
help page. Note that it uses the rule that 1 Kb = 1024 bytes (not 1000 as in your example).
Use the humanReadable() function in the gdata package. It has options to report the size in base 1000 ('SI') or base 1024 ('IEC') units, and it is also vectorized so you can process an entire vector of sizes at the same time.
For example:
> humanReadable(c(60810, 124141, 124, 13412513), width=4)
[1] "60.8 kB" "124 kB" "124 B" "13.4 MB"
> humanReadable(c(60810, 124141, 124, 13412513), standard="IEC", width=4)
[1] "59.4 KiB" "121 KiB" "124 B" "12.8 MiB"
I'm currently working to prepare release 2.16.0 of gdata, which adds the ability to indicate which unit you would like to use for reporting the sizes, as well as "Unix"-style units.
> humanReadable(c(60810, 124141, 124, 13412513), standard="SI", units="kB")
[1] " 60.8 kB" " 124.1 kB" " 0.1 kB" "13412.5 kB"
> humanReadable(c(60810, 124141, 124, 13412513), standard="IEC", units="KiB")
[1] " 59.4 KiB" " 121.2 KiB" " 0.1 KiB" "13098.2 KiB"
humanReadable(c(60810, 124141, 124, 13412513), standard="Unix", units="K")
[1] " 59.4 K" " 121.2 K" " 0.1 K" "13098.2 K"
-Greg [maintainer of the gdata package]
Update
CRAN has accepted gdata version 2.16.1, which supports standard="Unix"
and units=
options, and it should be available on a CRAN mirrors shortly.