df_apply
df_apply.Rd
Apply a function to qualifying columns in a data frame, a different function otherwise
Arguments
- .data
Data frame containing columns to apply functions to
- .f
Function to apply to columns that fit .condition()
- .condition
Condition to check to apply .f()
- .else
Function to apply to columns that do NOT fit .condition()
- ...
Additional arguments to be passed to .f()
Examples
n <- 7L
test_data <-
dplyr::tibble(
double = rnorm(n, 100, 10),
integer = (1L:n) * (1L:n),
character = LETTERS[1L:n],
factor = factor(letters[1L:n]),
logical = rep(c(TRUE, FALSE), length.out = n)
)
test_data
#> # A tibble: 7 × 5
#> double integer character factor logical
#> <dbl> <int> <chr> <fct> <lgl>
#> 1 93.5 1 A a TRUE
#> 2 101. 4 B b FALSE
#> 3 99.6 9 C c TRUE
#> 4 122. 16 D d FALSE
#> 5 110. 25 E e TRUE
#> 6 100. 36 F f FALSE
#> 7 102. 49 G g TRUE
df_apply(test_data, round, digits = -1)
#> # A tibble: 7 × 5
#> double integer character factor logical
#> <dbl> <dbl> <chr> <fct> <lgl>
#> 1 90 0 A a TRUE
#> 2 100 0 B b FALSE
#> 3 100 10 C c TRUE
#> 4 120 20 D d FALSE
#> 5 110 20 E e TRUE
#> 6 100 40 F f FALSE
#> 7 100 50 G g TRUE
test_data |> df_apply(mean, is.numeric)
#> # A tibble: 7 × 5
#> double integer character factor logical
#> <dbl> <dbl> <chr> <fct> <lgl>
#> 1 104. 20 A a TRUE
#> 2 104. 20 B b FALSE
#> 3 104. 20 C c TRUE
#> 4 104. 20 D d FALSE
#> 5 104. 20 E e TRUE
#> 6 104. 20 F f FALSE
#> 7 104. 20 G g TRUE
test_data |> df_apply(tolower, is.character)
#> # A tibble: 7 × 5
#> double integer character factor logical
#> <dbl> <int> <chr> <fct> <lgl>
#> 1 93.5 1 a a TRUE
#> 2 101. 4 b b FALSE
#> 3 99.6 9 c c TRUE
#> 4 122. 16 d d FALSE
#> 5 110. 25 e e TRUE
#> 6 100. 36 f f FALSE
#> 7 102. 49 g g TRUE
test_data |> df_apply(round, is.numeric, as.factor, digits = -1)
#> # A tibble: 7 × 5
#> double integer character factor logical
#> <dbl> <dbl> <fct> <fct> <fct>
#> 1 90 0 A a TRUE
#> 2 100 0 B b FALSE
#> 3 100 10 C c TRUE
#> 4 120 20 D d FALSE
#> 5 110 20 E e TRUE
#> 6 100 40 F f FALSE
#> 7 100 50 G g TRUE