【发布时间】:2017-07-05 19:18:30
【问题描述】:
我想创建一个升级版的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 包有任何想法,以潜在地避免对字符强制因素,或者是否有人有任何一般性的建议来提高性能同时保持相同的功能(我想坚持tidyverse 语法)。谢谢!
【问题讨论】:
-
为什么不直接
do.call(rbind, list(df1, df2))? -
suppressWarnings或purrr::quietly?