file.size() function returns the file size in Bytes. How can we convert the returned bytes into KB, MB, GB or TB accordingly?
For e.g.
255Bytes = 255B
19697Bytes = 19.24KB
13230426Bytes = 12.62MB
We could try a brute force approach using case_when from the dplyr package:
library(dplyr)
input <- 123456 # numerical input as number of bytes
output <- case_when(
input < 1000 ~ paste0(input, "B"),
input < 1000000 ~ paste0(input / 1000, "KB"),
input < 1000000000 ~ paste0(input / 1000000, "MB"),
input < 1000000000000 ~ paste0(input / 1000000000, "GB"),
input < 1000000000000000 ~ paste0(input / 1000000000, "TB"),
TRUE ~ paste0(input, "B") # for anything larger than 999TB, just report bytes
)
output
[1] "123.456KB"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With