Search code examples
rstringsplittype-conversion

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?

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