0

Quick question - How to convert all (or some: e.g. cols=1:5) columns at once (in one line) to another type (lets say integer), using dplyr.

A data to play with: df <- diamonds %>% slice(1:3) %>% select (5:10)

NB: I know how to do it in data.table:

dt <- df %>% data.table; 
cols=1:5
dt[ , (cols):=lapply(.SD, as.integer), .SDcol=cols]
IVIM
  • 2,167
  • 1
  • 15
  • 41

1 Answers1

1

You can use across to apply same function to multiple columns.

library(dplyr)

df %>% mutate(across(all_of(cols), as.integer))
#In old version we use `mutate_at`
#df %>%  mutate_at(all_of(cols), as.integer)

#  depth table price     x     y     z
#  <int> <int> <int> <int> <int> <dbl>
#1    61    55   326     3     3  2.43
#2    59    61   326     3     3  2.31
#3    56    65   327     4     4  2.31

Using all_of is not required but it is a good practice to use it when we use variables which are not present in the dataframe.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213