convert strings in multiple column to numeric

How can I convert string entries of several columns into numeric at once?

For example, if I have 'red' in row 1&3 of column 1, row 2 of column 2, and row 3 of column 3 - how can I make sure that when I convert all three columns into numeric, all the 'red's will get assigned the same numeric number? --this is just a simplified example - as I am working with columns filled with thousands of unique entries

|col 1|col 2|col 3|
|red |blue | blue|
|gray|red |blue |
|red |gray |red |

into:

|col 1|col 2|col 3|
| 1 |2 | 2 |
|3 |1 |2 |
|1 |3 |1 |

Thanks a lot!

library(tidyverses)
(df1 <-tibble(
  col_1 = c("r","g","r"),
  col_2 = c("b","r","g"),
  col_3 = c("b","b","r")
))

# get all character unique values
(unq <- unique(unlist(df1 %>% select_if(is.character))))

(df2 <- mutate(df1,
               across(where(is.character),
                     ~factor(.x,levels=unq))))

(df3 <- mutate(df2,
               across(where(is.factor),
                      as.integer)))

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.