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
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"
I have found various solutions in other programming languages. But this post has a solution suggested by @Rohit Jain which is working fine. With small tweaks implemented it in an R function:
file_size_formated <- function(size){
k = size/1024.0 ^ 1
m = size/1024.0 ^ 2
g = size/1024.0 ^ 3
t = size/1024.0 ^ 4
if (t > 1) {
outSize = paste0(round(t,2),"TB")
} else if (g > 1) {
outSize = paste0(round(g,2),"GB")
} else if (m > 1) {
outSize = paste0(round(m,2),"MB")
} else if (k > 1) {
outSize = paste0(round(k,2),"KB")
} else{
outSize = paste0(round(size,2),"B")
}
return(outSize)
}
Let's say you want to get file sizes for all the files in "www" folder on your device:
# Normal output
file.size(list.files("www",full.names = TRUE))
[1] 255 307 856 1205 1038 5940 250 3940 328 1593 53938 59061210 3750711 16251 42756
[16] 6709 19697 13230426
# Function Output
sapply(file.size(list.files("www",full.names = TRUE)),file_size_formated)
[1] "255B" "307B" "856B" "1.18KB" "1.01KB" "5.8KB" "250B" "3.85KB" "328B" "1.56KB" "52.67KB" "56.33MB" "3.58MB" "15.87KB"
[15] "41.75KB" "6.55KB" "19.24KB" "12.62MB"