piper180
piper180

Reputation: 361

How do I convert all numeric columns to character type in my dataframe?

I would like to do something more efficient than

dataframe$col <- as.character(dataframe$col)

since I have many numeric columns.

Upvotes: 4

Views: 1294

Answers (2)

TarJae
TarJae

Reputation: 78917

All said by master akrun! Here is a data.table alternative. Note it converts all columns to character class:

library(data.table)
data.table::setDT(df)
df[, (colnames(df)) := lapply(.SD, as.character), .SDcols = colnames(df)]

Upvotes: 4

akrun
akrun

Reputation: 886938

In base R, we may either use one of the following i.e. loop over all the columns, create an if/else conditon to change it

dataframe[] <- lapply(dataframe, function(x) if(is.numeric(x)) 
           as.character(x) else x)

Or create an index for numeric columns and loop only on those columns and assign

i1 <- sapply(dataframe, is.numeric)
dataframe[i1] <- lapply(dataframe[i1], as.character)

It may be more flexible in dplyr

library(dplyr)
dataframe <- dataframe %>%
        mutate(across(where(is.numeric), as.character))

Upvotes: 5

Related Questions