0

Consider the following table:

df <- tibble(
  col1 = sample(10:1000, 5),
  col2 = sample(1000:10000, 5),
  col3 = sample(100:500, 5)
)

I'd like to divide col1 and col3 by 10, and col2 by 1000.

I can do this by using 2 mutate_at functions like so:

df %>% 
  mutate_at(
    c("col1", "col3"),
    ~ .x / 10
  ) %>% 
  mutate_at(
    "col2",
    ~ .x / 1000
  )

Is there a way to do the above in a single mutate_x function?

1
  • 3
    In the next release of dplyr, you could use across and do this with one mutate. df %>% mutate(across(col1, col2), ~.x/10, across(col3), ~.x/1000) . See here tidyverse.org/blog/2020/04/dplyr-1-0-0-colwise Commented Apr 9, 2020 at 7:23

1 Answer 1

2

As Ronak says, across will replace the scoped verbs _at, _if, _all in the newest version of dplyr. You can start using it prior to its CRAN release by doing remotes::install_github("tidyverse/dplyr").

The correct use of across is slightly different than in his comment above.

df %>% mutate(across(c(col1, col2), ~.x/10), 
              across(col3, ~.x/1000))
#> # A tibble: 5 x 3
#>    col1  col2  col3
#>   <dbl> <dbl> <dbl>
#> 1  87.3  127. 0.324
#> 2  19.5  752. 0.194
#> 3  74.3  972. 0.197
#> 4  42.5  258. 0.116
#> 5  88.6  749. 0.11
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.