会计与申请不起作用

时间:2018-08-10 19:41:16

标签: r apply formattable

我正在尝试使用apply中accounting包中的formattable,但似乎不起作用-

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

我想要的是-

           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

1 个答案:

答案 0 :(得分:3)

您可能希望将其保留为数据框,在这种情况下,apply不是正确的工具。它将始终为您提供矩阵。

您可能需要以下选项之一:

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

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

或使用dplyr之类的东西

temp %>% 
  mutate_at(.vars = cols,.funs = accounting,digits = 0)