Home > Back-end >  Add a comma after two digits in R?
Add a comma after two digits in R?

Time:11-13

I would like to add a comma between numbers in all the column.

My data is a percentage, but it's delivered this way:

Percentage

3456
4444
325

Expected values:

Percentage

34,56
44,44
32,5


When I use gsub o sub I can't conserve my column as numeric. It doesn't matter if I use "." or "," the result is character.

Thanks!

CodePudding user response:

We can make use of comma from formattable which will modify the format while keeping the numeric as it is

df1$Percentage <- formattable::comma(df1$Percentage, big.interval = 2, digits = 0)

-checking

> df1
  Percentage
1      34,56
2      44,44
3       3,25
> str(df1)
'data.frame':   3 obs. of  1 variable:
 $ Percentage: 'formattable' int  34,56 44,44 3,25
  ..- attr(*, "formattable")=List of 4
  .. ..$ formatter: chr "formatC"
  .. ..$ format   :List of 4
  .. .. ..$ format      : chr "f"
  .. .. ..$ big.mark    : chr ","
  .. .. ..$ digits      : num 0
  .. .. ..$ big.interval: num 2
  .. ..$ preproc  : NULL
  .. ..$ postproc : NULL

It is also possible to do calculations as it is a numeric column

> df1$Percentage * 100
[1] 34,56,00 44,44,00 3,25,00 

data

df1 <- structure(list(Percentage = c(3456L, 4444L, 325L)), class = "data.frame", row.names = c(NA, 
-3L))

CodePudding user response:

We can make it in another way:

library(stringr)
library(dplyr)

x <- c("3333", "4223", "34215")

P1 <- x %>%
        str_replace_all("(^\\d{2})", "\\1.") %>%
        as.double() %>%
        data.frame() 

colnames()[1] <- "Percentage"

Result:

> P1
  Percentage
1     33.330
2     42.230
3     34.215
  • Related