Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert string vector with \n and k values into numeric with

I have a following vector. Where, we have \n, and k with numeric data, and k represent the 1000.

v <- c("2.2K\n", "3\n", "1K\n", "1", "45", "5\n")

> v
> [1] "2.2K\n" "3\n"    "1K\n"   "1"      "45"     "5\n"

I need to convert the above vector into numeric vector as follows.

> v
 [1] "2200" "3"    "1000" "1"    "45"   "5"

Can anyone help me?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When I used the following command, I got solved the \n, but could not solve the K.

> as.numeric(v)
[1] NA  3 NA  1 45  5

>Solution :

You can use scan + gsub

> as.numeric(scan(text = gsub("K", "e3", v), what = "", quiet = TRUE))
[1] 2200    3 1000    1   45    5
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading