How to change the column’s type using dplyr in r?
n dplyr
, you can use the mutate()
function across()
to change the data type of multiple columns while keeping one column the same type. Here’s an example:
library(dplyr)
# Example dataframe
df <- data.frame(
var1 = c("1", "2", "3"),
var2 = c(4.5, 5.6, 6.7),
var3 = c(TRUE, FALSE, TRUE)
)
# Change data types while keeping var3 as logical
df_new <- df %>%
mutate(across(where(is.character), as.integer), # Change character columns to integers
across(where(is.numeric), as.character), # Change numeric columns to characters
.keep = "unused") # Keep var3 column as it is
# Check the new dataframe
str(df_new)
The above code mutate()
is used across()
to specify the columns to be transformed. where()
is used to select columns based on their data types. In this example, where(is.character)
it selects columns with character data type and where(is.numeric)
columns with numeric data type.
Inside across()
, as.integer
and as.character
are used to convert the selected columns to the desired data types. The .keep = "unused"
argument ensures that the column specified .keep
is not modified and its original data type is preserved.
After executing the code, the df_new
data frame will have the modified data types for var1 and var2 while keeping var3 as logical. The str()
function is used to print the structure of the new data frame to verify the changes.