在R语言中是否有标准函数可以将代表字节数的字符串,例如
- 11855276K
- 113M
- 2.40G
转换为整数字节数?
我发现gdata包中有humanReadable
函数,但是它是进行相反的转换。我知道我可以解析字符串然后自己执行计算,但我想知道是否已经存在这样的功能。
x <- c("11855276K", "113M", "2.40G", "1234")
convb <- function(x){
ptn <- "(\\d*(.\\d+)*)(.*)"
num <- as.numeric(sub(ptn, "\\1", x))
unit <- sub(ptn, "\\3", x)
unit[unit==""] <- "1"
mult <- c("1"=1, "K"=1024, "M"=1024^2, "G"=1024^3)
num * unname(mult[unit])
}
convb(x)
[1] 12139802624 118489088 2576980378 1234
## Create some number of bytes of differing units, and "convert" to fs_bytes
sizes <- c("11855276K", "113M", "2.40G", "1234") |>
fs::fs_bytes()
## It picks sensible human-readable default units for printing
sizes
## 11.31G 113M 2.4G 1.21K
## The data is stored as numeric
str(sizes)
## 'fs_bytes' num [1:4] 11.31G 113M 2.4G 1.21K
## As a result, you can perform numeric operations on them
sum(sizes)
## 13.8G
## Use as.numeric to print the values as bytes
as.numeric(sizes)
## [1] 12139802624 118489088 2576980378 1234