1

I am trying to use accounting from the formattable package within apply, and it does not seem to working -

library(formattable)
set.seed(4226)
temp = data.frame(a = sample(1000:50000, 10), b = sample(1000:50000, 10), 
                    c = sample(1000:50000, 10), d = sample(1000:50000, 10))

temp
       a     b     c     d
1  45186 17792 43363 17080
2  26982 25410  2327 17982
3  45204 39757 29883  4283
4  27069 21334 10497 28776
5  47895 46241 22743 36257
6  30161 45254 21382 42275
7  18278 28936 27036 23620
8  31199 30182 10235  7355
9  10664 40312 28324 20864
10 45225 45545 44394 13364


apply(temp, 2, function(x){x = accounting(x, digits = 0)})

          a     b     c     d
 [1,] 45186 17792 43363 17080
 [2,] 26982 25410  2327 17982
 [3,] 45204 39757 29883  4283
 [4,] 27069 21334 10497 28776
 [5,] 47895 46241 22743 36257
 [6,] 30161 45254 21382 42275
 [7,] 18278 28936 27036 23620
 [8,] 31199 30182 10235  7355
 [9,] 10664 40312 28324 20864
[10,] 45225 45545 44394 13364

What I want is -

           a      b      c      d
 [1,] 45,186 17,792 43,363 17,080
 [2,] 26,982 25,410  2,327 17,982
 [3,] 45,204 39,757 29,883  4,283
 [4,] 27,069 21,334 10,497 28,776
 [5,] 47,895 46,241 22,743 36,257
 [6,] 30,161 45,254 21,382 42,275
 [7,] 18,278 28,936 27,036 23,620
 [8,] 31,199 30,182 10,235  7,355
 [9,] 10,664 40,312 28,324 20,864
[10,] 45,225 45,545 44,394 13,364
phil_t
  • 851
  • 2
  • 7
  • 17
  • 1
    Maybe of interest: https://stackoverflow.com/a/28724756/ so `res = accounting(unlist(temp), digits = 0); dim(res) <- dim(temp); dimnames(res) <- dimnames(temp)` is an option, sort of. – Frank Aug 10 '18 at 20:21

1 Answers1

3

You probably want to keep things as a data frame, in which case apply is not the right tool. It will always give you a matrix back.

You might want one of the following options:

temp[cols] <- lapply(temp[cols], function(x){accounting(x, digits = 0)})

or

as.data.frame(lapply(temp[cols], function(x){accounting(x, digits = 0)}))

or using dplyr something like:

temp %>% 
  mutate_at(.vars = cols,.funs = accounting,digits = 0)
joran
  • 169,992
  • 32
  • 429
  • 468
  • I am not having an issue with the structure of the output but with the content of the output -the accounting format commas are not present. I am getting the same results with `sapply()` or `as.data.frame(lapply())` as well. – phil_t Aug 10 '18 at 20:13
  • 1
    I guess matrices can only hold atomic vectors or lists, so the extra attributes get lost and only the core data is kept. If you really want a matrix @phil_t you could write a custom function that converts as.character after applying formatting. – Frank Aug 10 '18 at 20:15
  • I’m away from my computer; anyone who feels comfortable should feel free to edit this to math the OP desire to convert all columns rather than just some. – joran Aug 10 '18 at 20:34