r - Converting 1M to 1000000 elegantly -


i want convert:

library(data.table) market.cap <- data.table(cap=c("1b", "10m", "2m"))    cap 1  1b 2 10m 3  2m 

to:

      cap 1 1000000000 2   10000000 3    2000000 

here's solution. works, involves adding column, know isn't necessary. what's better way?

market.cap[, cap1 := cap] market.cap$cap = sapply(market.cap$cap, function(x) (as.numeric(temp <- gsub("b", "", x)) * 1000000000)) market.cap$cap1 = sapply(market.cap$cap1, function(x) (as.numeric(temp <- gsub("m", "", x)) * 1000000)) m = data.frame(x = na.omit(market.cap$cap)) b = data.frame(x = na.omit(market.cap$cap1)) rbind(m,b) 

here's own attempt:

market.cap[ , cap1 := {   sf <- gsub("[0-9]", "", cap)   as.numeric(gsub("[^0-9]", "", cap)) * 1000 ^ (2 + (sf == "b"))}] 

the following approach may prove faster since doesn't need waste effort on running cap through regex twice:

market.cap[ , cap1 := {   x<- do.call("rbind", strsplit(cap, split = "(?=[bm])", perl = true))   as.numeric(x[ , 1l]) * 1000 ^ (2 + (x[ , 2l] == "b"))}] 

and following may prove fastest since tstrsplit has been optimized in data.table:

market.cap[ , cap1 := {   x <- tstrsplit(cap, split = "(?=[bm])", perl = true)   as.numeric(x[[1l]]) * 1000 ^ (2 + (x[[2]] == "b"))}] 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -