If one wanted to apply a function to one or more columns, optionally based on some criteria, it seems that there are two identical ways to do this with Tidyverse packages. I'm wondering if there's any reason to prefer one over the other?
For example, if one wanted to convert all numeric columns to character, you could do either of the following:
library(dplyr, warn.conflicts = FALSE)
library(purrr)
library(ggplot2)
mpg |>
mutate(across(where(is.numeric), as.character)) |>
slice_head(n = 5)
#> # A tibble: 5 × 11
#> manufacturer model displ year cyl trans drv cty hwy fl class
#> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
#> 1 audi a4 1.8 1999 4 auto(l5) f 18 29 p compa…
#> 2 audi a4 1.8 1999 4 manual(m5) f 21 29 p compa…
#> 3 audi a4 2 2008 4 manual(m6) f 20 31 p compa…
#> 4 audi a4 2 2008 4 auto(av) f 21 30 p compa…
#> 5 audi a4 2.8 1999 6 auto(l5) f 16 26 p compa…
mpg |>
modify_if(is.numeric, as.character) |>
slice_head(n = 5)
#> # A tibble: 5 × 11
#> manufacturer model displ year cyl trans drv cty hwy fl class
#> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
#> 1 audi a4 1.8 1999 4 auto(l5) f 18 29 p compa…
#> 2 audi a4 1.8 1999 4 manual(m5) f 21 29 p compa…
#> 3 audi a4 2 2008 4 manual(m6) f 20 31 p compa…
#> 4 audi a4 2 2008 4 auto(av) f 21 30 p compa…
#> 5 audi a4 2.8 1999 6 auto(l5) f 16 26 p compa…
Or, if you just wanted to change the year column, either of the following would work:
library(dplyr, warn.conflicts = FALSE)
library(purrr)
library(ggplot2)
mpg |>
mutate(year = as.character(year)) |>
slice_head(n = 5)
#> # A tibble: 5 × 11
#> manufacturer model displ year cyl trans drv cty hwy fl class
#> <chr> <chr> <dbl> <chr> <int> <chr> <chr> <int> <int> <chr> <chr>
#> 1 audi a4 1.8 1999 4 auto(l5) f 18 29 p compa…
#> 2 audi a4 1.8 1999 4 manual(m5) f 21 29 p compa…
#> 3 audi a4 2 2008 4 manual(m6) f 20 31 p compa…
#> 4 audi a4 2 2008 4 auto(av) f 21 30 p compa…
#> 5 audi a4 2.8 1999 6 auto(l5) f 16 26 p compa…
mpg |>
modify_at('year', as.character) |>
slice_head(n = 5)
#> # A tibble: 5 × 11
#> manufacturer model displ year cyl trans drv cty hwy fl class
#> <chr> <chr> <dbl> <chr> <int> <chr> <chr> <int> <int> <chr> <chr>
#> 1 audi a4 1.8 1999 4 auto(l5) f 18 29 p compa…
#> 2 audi a4 1.8 1999 4 manual(m5) f 21 29 p compa…
#> 3 audi a4 2 2008 4 manual(m6) f 20 31 p compa…
#> 4 audi a4 2 2008 4 auto(av) f 21 30 p compa…
#> 5 audi a4 2.8 1999 6 auto(l5) f 16 26 p compa…
Is there any reason to prefer one over the other, other than possibly not having to have the extra import of purrr? Or are these identical?
