【问题标题】:How to convert factors to characters using ```purrr:map()``` and ```mutate_if```` in R?如何在 R 中使用 ```purrr:map()``` 和 ```mutate_if``` 将因子转换为字符?
【发布时间】:2020-03-09 14:52:34
【问题描述】:

我正在尝试将列表对象中的因子转换为字符。

我的第一次尝试是 purrr::mapmutate_if(is.factor,as.character) 的组合,但这不起作用。我用 Google 搜索了错误消息,但没有找到问题的答案。

我求助于使用base::lapply 来完成工作(确实如此)。

但是,我无法通过 purrr::map 方法发现错误。 有什么问题?

以下代码是我所面临情况的一个工作示例。

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"

【问题讨论】:

    标签: r dplyr purrr


    【解决方案1】:

    问题是mutatetbl_df/data.frame 上工作,cut_modif 的输出是vector,所以本质上,它是vectorslist,为此可以使用map_if

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

    如果我们还想用mutate,转换成data.frame/tbl_df再应用

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

    另外,请注意,通过使用匿名函数调用 (~),可以避免多次调用 map

    【讨论】:

    • 在我第一次使用 SO 时,我被告知要等待几分钟才能接受正确的答案。谢谢你的反馈,阿克伦。非常精确、简洁而又富有洞察力。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 2018-07-18
    • 1970-01-01
    • 2017-05-06
    相关资源
    最近更新 更多