2

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 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.