Home > Software engineering >  How can I mutate all columns to change class using dplyr in R?
How can I mutate all columns to change class using dplyr in R?

Time:01-28

I have a dataset let say it df which has 100 columns of different type of column vectors (class), i.e character, integer,double etc.

How I can use dplyr or any other tidyverse like functions in order to change the class of columns? I want to mutate_if across all columns that are integer to double. And then keep only the as.double columns and drop the character columns?

Is there a way in R ? Any help ?

CodePudding user response:

In both cases you can use tidy select calls to choose the correct columns:

library(dplyr)

df <- tibble(
  a = runif(100),
  b = sample(1:1000, 100),
  c = sample(letters, 100, replace = TRUE),
  d = rnorm(100),
  e = 101:200
)

df |> 
  mutate(across(where(is.integer), as.double)) |> 
  select(where(is.double))

#> # A tibble: 100 × 4
#>         a     b       d     e
#>     <dbl> <dbl>   <dbl> <dbl>
#>  1 0.196    468 -1.35     101
#>  2 0.373    865  0.123    102
#>  3 0.0250   534  0.131    103
#>  4 0.622    388  0.426    104
#>  5 0.354    670  0.625    105
#>  6 0.806    474 -1.15     106
#>  7 0.282    318 -1.27     107
#>  8 0.813    331  1.05     108
#>  9 0.360    165 -0.765    109
#> 10 0.0929   645 -0.0232   110
#> # … with 90 more rows
  • Related