Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

I would like to do something more efficient than

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

since I have many numeric columns.

like image 400
piper180 Avatar asked Oct 19 '25 09:10

piper180


1 Answers

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))
like image 67
akrun Avatar answered Oct 21 '25 23:10

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!