Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we get the formated file size in KB, MB, GB, TB in R? [duplicate]

Tags:

r

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
like image 319
Abhishek Agnihotri Avatar asked Oct 15 '25 14:10

Abhishek Agnihotri


1 Answers

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"
like image 57
Tim Biegeleisen Avatar answered Oct 17 '25 03:10

Tim Biegeleisen