Search code examples
rdplyrroundingacross

R: Round a data frame with a specific formula across all columns with dplyr


I would like to use the following formula to round my whole data frame in R:

format(round(Df$`p-value`, digits=2), nsmall = 2)

Now, the code above is only for one column (just to show you).

I know dplyr is easy to use when I want to use the formula for my whole data frame as there is the across() function. I tried the following:

Df %>%
mutate(across(format(round(digits=2), nsmall = 2)))

However, I get an error, saying that "argument "x" is missing, with no default". I assume I need to make a small adjustment to the code but I couldn't figure out what I need to adjust? Could someone help me here please?

Thank you.


Solution

  • You forgot argument x in it. R is completely right. You need to get the dataframe (argument x) in the function which you want to convert. In this case a "." represents the dataframe, because its dplyr. You mutate(across) was not working for me, so I decided to use mutate_all, which does the job perfectly.

    A %>%    mutate_all(~format(round(., digits=1), nsmall = 2))