我想创建一个dplyr::bind_rows的替代版本,当我们尝试合并的dfs中存在因子列时,它会避免出现Unequal factor levels: coercing to character警告(它也可能具有非因子列)。这是一个例子:

df1 <- dplyr::data_frame(age = 1:3, gender = factor(c("male", "female", "female")), district = factor(c("north", "south", "west")))
df2 <- dplyr::data_frame(age = 4:6, gender = factor(c("male", "neutral", "neutral")), district = factor(c("central", "north", "east")))


然后bind_rows_with_factor_columns(df1, df2)返回(无警告):

dplyr::data_frame(
  age = 1:6,
  gender = factor(c("male", "female", "female", "male", "neutral", "neutral")),
  district = factor(c("north", "south", "west", "central", "north", "east"))
)


这是我到目前为止的内容:

bind_rows_with_factor_columns <- function(...) {
  factor_columns <- purrr::map(..., function(df) {
      colnames(dplyr::select_if(df, is.factor))
  })

  if (length(unique(factor_columns)) > 1) {
      stop("All factor columns in dfs must have the same column names")
  }

  df_list <- purrr::map(..., function (df) {
    purrr::map_if(df, is.factor, as.character) %>% dplyr::as_data_frame()
  })

  dplyr::bind_rows(df_list) %>%
    purrr::map_at(factor_columns[[1]], as.factor) %>%
    dplyr::as_data_frame()
}


我想知道是否有人对如何合并forcats包有任何想法,从而有可能避免不得不将字符强制转换为字符,或者有人是否总体上有任何建议来提高其性能,同时保持相同的功能(我想d坚持使用tidyverse语法)。谢谢!

最佳答案

根据朋友的出色解决方案回答我自己的问题:

bind_rows_with_factor_columns <- function(...) {
  purrr::pmap_df(list(...), function(...) {
    cols_to_bind <- list(...)
    if (all(purrr::map_lgl(cols_to_bind, is.factor))) {
      forcats::fct_c(cols_to_bind)
    } else {
      unlist(cols_to_bind)
    }
  })
}

08-20 01:59