Hugo
Hugo

Reputation: 346

How to convert factors to characters using ```purrr:map()``` and ```mutate_if```` in R?

I am trying to convert factors inside list objects to characters.

My first attempt was a combination of purrr::map with mutate_if(is.factor,as.character) but this did not work. I Googled the error message but didn't find an answer to my question.

I resorted to using the base::lapply to get the work done (and it did).

However, I cannot spot the mistake with my purrr::map approach. What is wrong with it?

The following code is a working example of the situation I'm facing.

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(purrr)

a_matrix = matrix(data = sample(100,100, replace = T),nrow = 10)

a_df = data.frame(a_matrix)

cut_modif = function(x) {
  cut(x,
      breaks = quantile(x),
      labels = c("A", "B", "C", "D"),
      include.lowest = T,
      right = T
  )
}

# This one works 
myResults = map(a_df,cut_modif) 
myResults = lapply(myResults, as.character)


# This one DOES NOT work
myResults = map(a_df,cut_modif) %>% 
            map(mutate_if(is.factor, as.character))
#> Error in UseMethod("tbl_vars"): no applicable method for 'tbl_vars' applied to an object of class "function"

Upvotes: 1

Views: 574

Answers (1)

akrun
akrun

Reputation: 887591

Issue is that mutate works on tbl_df/data.frame, the output from cut_modif is a vector, so essentially, it is a list of vectors and for that map_if can be used

library(dplyr)
library(purrr)
map(a_df,cut_modif) %>% 
          map_if(is.factor, as.character)

If we still want to use mutate, convert to a data.frame/tbl_df and then apply

map(a_df, ~ cut_modif(.x) %>%
                tibble(cutCol = .) %>%
                mutate_if(is.factor, as.character))

Also, note that by making use of anonymous function call (~), multiple calls to map can be avoided

Upvotes: 3

Related Questions