JFG123
JFG123

Reputation: 597

Applying mutate to multiple columns and rows in dplyr

A pretty simple question but has me dumbfounded.

I have a table and am trying to round each column to 2 decimal places using mutate_all (or another dplyr function). I know this can be done with certain apply functions but I like the dplyr/tidyverse frame work.

DF = data.frame(A = seq(from = 1, to = 2, by = 0.0255),
           B = seq(from = 3, to = 4, by = 0.0255))

Rounded.DF = DF%>%
  mutate_all(funs(round(digits = 2)))

This does not work however and just gives me a 2 in every column. Thoughts?

Upvotes: 2

Views: 743

Answers (1)

davsjob
davsjob

Reputation: 1950

You need a "dot" in the round function. The dot is a placeholder for where mutate_all should place each column that you are trying to manipulate.

Rounded.DF = DF%>%
  mutate_all(funs(round(., digits = 2)))

To make it more intuitive you can write the exact same thing as a custom function and then reference that function inside the mutate_all:

round_2_dgts <- function(x) {round(x, digits = 2)}

Rounded.DF = DF%>%
  mutate_all(funs(round_2_dgts))

Upvotes: 3

Related Questions