1

I'm trying to add thousands separator into certain column values. In this case column x2 and x1, but I failed to so so. Here is my code :

my_data <- data.frame(x1 = c("a","b", "c"),           
                  x2 = c(10000, 5000, 5000),
                  x3 = 1001:1003)
col_conv <- c("x3","x2")
my_data_updated <- my_data
my_data_updated[ , col_conv] <- lapply(my_data_updated[ , col_conv],
                                       function(x){ as.numeric(gsub(",", "", x)) })

the data frame format is not changing

thank you

2 Answers2

1

To do this, you will have to create your own class:

Check these solutions and explanations here and here

In your case write these four functions:

my_numbers <- function(x) structure(x, class = c('my_numbers', 'numeric'))  
format.my_numbers <- function(x,...)NextMethod(sci = FALSE, big.mark=',')
print.my_numbers <- function(x,...) print(format(x), quote = FALSE)    
'[.my_numbers' <- function(x,...,drop = FALSE)  my_numbers(NextMethod('['))

Now run:

x <- my_numbers(c(1000000, 1000, 20003))
x
[1] 1,000,000     1,000    20,003

And you can do maths on x:

x * 2
[1] 2,000,000     2,000    40,006

Now for your data.frame:

my_data[c('x2', 'x3')] <- lapply(my_data[c('x2', 'x3')], my_numbers)
my_data

  x1     x2    x3
1  a 10,000 1,001
2  b  5,000 1,002
3  c  5,000 1,003
Onyambu
  • 67,392
  • 3
  • 24
  • 53
0

Try this

my_data_result<-my_data%>% 
  mutate(across(x2:x3, ~formatC(., format="d", big.mark=",")))
Yomi.blaze93
  • 401
  • 3
  • 10
  • I tried to do this, but my data class become character. I still need to use it as numeric values. – Erwin Hidayat Jun 19 '22 at 03:57
  • @ErwinHidayat what's the purpose for doing that? you can have an object print in a particular way if you define a new method, but that will be very narrow in scope, eg, if you wrote to a csv, there would be no formatting, it would only affect how it looks when you print to the console – rawr Jun 19 '22 at 04:39