Converting kilobytes, megabytes etc. to bytes in R

戏子无情 提交于 2019-12-10 12:41:53

问题


Is there a standard function in R to convert strings representing numbers of bytes such as

  • 11855276K
  • 113M
  • 2.40G

to integer numbers of bytes?

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.


回答1:


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

You may want to add additional units and conversions, e.g. terabytes.



来源:https://stackoverflow.com/questions/10910688/converting-kilobytes-megabytes-etc-to-bytes-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!