sara bokeh
sara bokeh

Reputation: 13

How to replace string from numeric value in R?

I have a dataset that contains the number of app installers, the data recorded with units M and K, like: 19M, 199K.

How to replace the prefixes with their values to convert values to numeric.

k to e+3

M to e+6

Upvotes: 1

Views: 197

Answers (1)

Edward
Edward

Reputation: 19514

Edit: For values that have non-integer values.

x <- c("19M","20K","1K", "1.25M", "1.5K"); x
x <- sub("M", "e6", x); x
x <- sub("K", "e3", x); x
as.numeric(x)
[1] 19000000    20000     1000  1250000     1500

For integer values, the following is sufficient.

x <- c("19M","20K","1K")

x <- sub("M","000000", x)
x <- sub("K","000", x)
as.numeric(x)

1.9e+07 2.0e+04 1.0e+03

Upvotes: 2

Related Questions