将千字节,兆字节等转换为R中的字节 [英] Converting kilobytes, megabytes etc. to bytes in R
本文介绍了将千字节,兆字节等转换为R中的字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
R中是否有标准函数来转换表示字节数的字符串,例如
Is there a standard function in R to convert strings representing numbers of bytes such as
- 11855276K
- 113M
- 2.40G
转换为整数字节?
我在gdata包中遇到了 humanReadable
,但是这样做是相反的。我知道我可以解析字符串,然后自己进行数学运算,但是我想知道是否已经存在某些东西。
I came across humanReadable
in the package gdata, but this does the conversion the other way round. I know that I can parse the string and then do the maths myself, but I wondered whether something exists already.
推荐答案
一个简单的函数来做到这一点:
A simple function to do this:
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
您可能想添加其他单位和转化,例如TB。
You may want to add additional units and conversions, e.g. terabytes.
这篇关于将千字节,兆字节等转换为R中的字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文