user3022875
user3022875

Reputation: 9018

R format a data table with commas

I have a data table and I want to format the number in it with commas.

her is my code:

data<- data.frame(x = c(100000,4000000,6000000),y=c(43125343243, 3421341234,  324134314343))
data
formatC(data, format="d", big.mark=',')
data

I am getting an error:

  Error in formatC(data, format = "d", big.mark = ",") : 
   (list) object cannot be coerced to type 'integer'
 In addition: Warning message:
 In formatC(data, format = "d", big.mark = ",") : class of 'x' was discarded

Any idea? Thank you!

Upvotes: 0

Views: 2528

Answers (2)

David Arenburg
David Arenburg

Reputation: 92282

The problem is that "data" is a dataframe and you are not specifying which column you want operate on. Though, for some reason formatC is not working on column y when format = "d" (for integers), so you could change it to format = "fg" (for real numbers) and loop it over your columns using apply. You could also just use the "normal" format too

apply(data, 2, function(x) formatC(x, format="fg", big.mark=','))
#                x                 y                
# [1,] "100,000"   "43,125,343,243" 
# [2,] "4,000,000" "3,421,341,234"  
# [3,] "6,000,000" "324,134,314,343"

or with the "normal" format

apply(data, 2, function(x) format(x, big.mark= ",", scientific = F))
#                x                 y                
# [1,] "  100,000" " 43,125,343,243"
# [2,] "4,000,000" "  3,421,341,234"
# [3,] "6,000,000" "324,134,314,343"

The second solution will require trimming the numbers, so I'll just stick with the first one

Upvotes: 2

merlin2011
merlin2011

Reputation: 75545

If you just want to dump it out to the screen, you can use write.csv without a filename argument:

write.csv(data)

If you want to remove row numbers and quotations, you can do:

write.csv(data, quote=F, row.names=F)

Output:

x,y
1e+05,43125343243
4e+06,3421341234
6e+06,324134314343

Upvotes: 1

Related Questions