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

Time:05-20

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.

CodePudding user response:

This should do it. You need to specify the .fns argument by name or the formula will be matched by position to the first argument of across, .cols.

DF %>% mutate( across( .fns = ~ format(round(.x, digits = 2), nsmall = 2) )

CodePudding user response:

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))

CodePudding user response:

First I create some random data:

Df <- data.frame(v1 = c(1.21,3.21,2.2,1.11),
                 v2 = c(1.333, 2.22,1.1111,2.1))

You can use the following code:

library(dplyr)
Df %>%
  mutate(across(everything(~format(round(digits=2), nsmall = 2))))

Output:

    v1     v2
1 1.21 1.3330
2 3.21 2.2200
3 2.20 1.1111
4 1.11 2.1000
  • Related