Home > OS >  Adding thousand separator in data frame column in r
Adding thousand separator in data frame column in r

Time:06-19

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

CodePudding user response:

Try this

my_data_result<-my_data%>% 
  mutate(across(x2:x3, ~formatC(., format="d", big.mark=",")))

CodePudding user response:

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
  •  Tags:  
  • r
  • Related