Format all columns with mutate_all in dplyr

I am looking for table formatting using scales::dollar inside mutate_all .

Desired Results

Desired results can be obtained using sapply :

 >> sapply(mtcars, scales::dollar) mpg cyl disp hp drat wt qsec vs am gear carb [1,] "$21.00" "$6" "$160.00" "$110" "$3.90" "$2.62" "$16.46" "$0" "$1" "$4" "$4" [2,] "$21.00" "$6" "$160.00" "$110" "$3.90" "$2.88" "$17.02" "$0" "$1" "$4" "$4" [3,] "$22.80" "$4" "$108.00" "$93" "$3.85" "$2.32" "$18.61" "$1" "$1" "$4" "$1" [4,] "$21.40" "$6" "$258.00" "$110" "$3.08" "$3.22" "$19.44" "$1" "$0" "$3" "$1" 

Problem

Trying to achieve the same results using the dplyr pipeline and scales::dollar :

 mtcars %>% mutate_all(funs(scales::dollar(.))) 

fails:

 Error in vapply(dots[missing_names], function(x) make_name(x$expr), character(1)) : values must be length 1, but FUN(X[[1]]) result is length 3 

Further intelligence

You can try a primitive workaround:

 mtcars %>% mutate_each(funs(as.character(paste0("$", .)))) 

results:

 >> mtcars %>% mutate_each(funs(as.character(paste0("$", .)))) mpg cyl disp hp drat wt qsec vs am gear carb 1 $21 $6 $160 $110 $3.9 $2.62 $16.46 $0 $1 $4 $4 2 $21 $6 $160 $110 $3.9 $2.875 $17.02 $0 $1 $4 $4 3 $22.8 $4 $108 $93 $3.85 $2.32 $18.61 $1 $1 $4 $1 

Following a similar discussion , this approach can be easily developed to create the desired currency format, but this is not the point.

Question

  • Why scales::dollar(.) mutate_all when applied to mutate_all (or mutate_each )? when applied to vector elements, it works as expected, whether this behavior should be replicated along the observations available in the column when they are passed inside mutate_all / mutate_each :

     >> scales::dollar(c(1, 1e4)) [1] "$1" "$10,000" 
+5
source share
1 answer

We need to wrap as.character as this seems like an error when we use package::function in funs . Documented here

 mtcars %>% mutate_each(funs(as.character(scales::dollar(.)))) 

Additionally, the mutate_each function becomes obsolete based on the @Frank blog link, so we can use mutate_at

 mtcars %>% mutate_at(names(.), funs(as.character(scales::dollar(.)))) 

The tool would be to download the package and then call without ::

 library(scales) mtcars %>% mutate_at(names(.), funs(dollar(.))) 

or

 mtcars %>% mutate_at(names(.), dollar) 
+4
source

Source: https://habr.com/ru/post/1266175/


All Articles