We can use gsubfn
, match the non-numeric element (\D
), replace that with the corresponding value
of the list
that matches the key
, and use eval(parse
to convert that to numeric value.
library(gsubfn)
options(scipen=999)
unname(sapply(gsubfn('\D', list(B= '*1e9', M= '*1e6'),
market.cap$cap), function(x) eval(parse(text=x))))
#[1] 1000000000 10000000 2000000
We can also use match
after extracting the numeric
and non-numeric parts, then use match
with a vector of letters (c('B', 'M')
) to get the numeric index and replace it with new values.
market.cap[, cap1 := as.numeric(sub('\D', '',
cap))*c(1e9, 1e6)[match( sub('\d+', '', cap), c('B', 'M'))]]
# cap cap1
#1: 1B 1000000000
#2: 10M 10000000
#3: 2M 2000000
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…