Convert 000 to K

Viewed 73

I have data as follows. I want to convert 000 to K.

x <- data.frame(categoreis = c('[0, 1000)','[1000,3000)', 'Total','[20000, 40000]'))

[0, 1000) should appear as [0, 1K). Similarly, [20000, 40000] should appear as [20K, 40K].

2 Answers

You can use gsub with the regexp 000\\b where \\b indicates a boundary.

gsub("000\\b", "K", x$categoreis)
#[1] "[0, 1K)"    "[1K,3K)"    "Total"      "[20K, 40K]"
´´´

I guess this happened after using cut, try to avoid the problem by setting the labels:

x$categories <- cut(x$someColumn, 
    breaks = c(0, 1000, 3000, 20000, 40000),
    labels = c("0-1K", "1K-3K", "3K-20K", "20K-40K"))
Related