Search code examples
rpurrr

Apply function only on integer columns using purrr::map_df


This is my code. I need to apply a simple function on integer columns in a dataframe using purrr::map_df function, but I need to maintain the character column:

fun1 <- function(x){(x - mean(x))/sd(x)}

df <- mtcars %>% rownames_to_column()

df %>% map_df(~  fun1(.x))

Solution

  • What is your expected output exactly? Something like this?

    library(tidyverse)
    
    fun1 <- function(x) {
      (x - mean(x)) / sd(x)
    }
    
    df <- mtcars  %>%
      rownames_to_column() %>%
      as_tibble()
    

    df %>%
      mutate(across(where(is.integer), fun1))
    
    # A tibble: 32 × 12
       rowname              mpg    cyl    disp     hp   drat       wt   qsec     vs     am   gear   carb
       <chr>              <dbl>  <dbl>   <dbl>  <dbl>  <dbl>    <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
     1 Mazda RX4          0.151 -0.105 -0.571  -0.535  0.568 -0.610   -0.777 -0.868  1.19   0.424  0.735
     2 Mazda RX4 Wag      0.151 -0.105 -0.571  -0.535  0.568 -0.350   -0.464 -0.868  1.19   0.424  0.735
     3 Datsun 710         0.450 -1.22  -0.990  -0.783  0.474 -0.917    0.426  1.12   1.19   0.424 -1.12 
     4 Hornet 4 Drive     0.217 -0.105  0.220  -0.535 -0.966 -0.00230  0.890  1.12  -0.814 -0.932 -1.12 
     5 Hornet Sportabout -0.231  1.01   1.04    0.413 -0.835  0.228   -0.464 -0.868 -0.814 -0.932 -0.503
     6 Valiant           -0.330 -0.105 -0.0462 -0.608 -1.56   0.248    1.33   1.12  -0.814 -0.932 -1.12 
     7 Duster 360        -0.961  1.01   1.04    1.43  -0.723  0.361   -1.12  -0.868 -0.814 -0.932  0.735
     8 Merc 240D          0.715 -1.22  -0.678  -1.24   0.175 -0.0278   1.20   1.12  -0.814  0.424 -0.503
     9 Merc 230           0.450 -1.22  -0.726  -0.754  0.605 -0.0687   2.83   1.12  -0.814  0.424 -0.503
    10 Merc 280          -0.148 -0.105 -0.509  -0.345  0.605  0.228    0.253  1.12  -0.814  0.424  0.735
    # … with 22 more rows
    # ℹ Use `print(n = ...)` to see more rows