Change the data types of multiple columns through there names in R

Viewed 98

Is there a way to change the data type of multiple columns at once in R only through there column names?

df
COlA   COLB COlC
sdf    12    34
sdsd   12    45
sdfa   45    34

COLB and COLC should be changed to integer at once by using there names and not through indexing ?

1 Answers

Using dplyr

library(dplyr)
df <- df %>%
    mutate(across(c(COLB, COlC), as.integer))

Or if there are many columns, specify a range (:) if they are in the sequence

df %>%
    mutate(across(COLB:COlC, as.integer))

Or if only the first column needs to be skipped, can use -

 df %>%
    mutate(across(-COLA, as.integer))

In base R, we can use lapply

nm1 <- names(df)[-1]
df[nm1] <- lapply(df[nm1], as.integer)

It is also possible to do this automatically with type.convert

type.convert(df, as.is = TRUE)
Related