I have a data frame with more than 1000 character columns. I want to recode certain character columns as numeric but keep other columns as characters. I hope to achieve this without manually including/excluding columns for recoding (aka the operation needs to be on the entire data frame). I tried using dplyr::recode and dplyr::case_when but the unrecoded columns were all coerced into NA or I had to convert all columns into numeric.
A toy dataset:
df = tibble(name = c('Tom', 'Sarah'), wealth = c('poor', 'wealthy'), health = c('poor', 'good'))
I think dplyr::recode and dplyr::case require all columns to be the same type after recoding, yet I don't want the 'name' column to be numeric.
I tried using:
df_recoded = df %>% mutate(across(everything(),~recode(
.,
'poor' = 1,
'good' = 2,
'wealthy' = 2,
.default = . #doesn't work
)))
Or
df_recoded = df %>% mutate(across(everything(),~case_when(
. == 'poor' ~ 1,
. == 'good' ~ 2,
. == 'wealthy' ~ 2,
TRUE ~ . # doesn't work.
)))
The desired output is:
#> # A tibble: 2 x 3
#> name wealth health
#> <chr> <dbl> <dbl>
#> 1 Tom 1 1
#> 2 Sarah 2 2