【发布时间】:2021-10-09 10:27:26
【问题描述】:
我有一个从多重插补中获得的数据集列表。我现在想在这个数据集列表中重新分类一个变量。我曾尝试使用 purrr 中的 map 函数,但按照下面的代码,我对此并不满意。
是否可以实际映射一个使用 purr 重新组合和重新编码变量的函数?
# download pacman package if not installed, otherwise load it
if(!require(pacman)) install.packages(pacman)
# loads relevant packages using the pacman package
pacman::p_load(
dplyr, # for pipes and manipulation
mice ) # for imputation
# make 10 dataset using mice
nhanes_imp <- parlmice(nhanes,
m = 10,
cluster.seed = 1234)
# mut imputed datasets into a list
nhanes_imp <- nhanes_imp$imp
# create function to categorise chl
chl_funct <- function(x) {
if (x == "0") {
"0 days"
} else if (x < 100) {
"< 100"
} else if (x >= 100 & x < 150) {
"100 - 149"
} else if (x >= 150 & x < 200) {
"150 - 199"
} else if (x >= 200) {
">= 200"
}
# use the new function to categorise the chl var
nhanes_imp %>%
map_df(.$chl,
chl_funct)
当我运行代码时,这是我得到的错误:
<error/rlang_error>
Can't convert a `data.frame` object to function
Backtrace:
1. nhanes_imp %>% map_df(.$chl, chl_funct)
2. purrr::map_df(., .$chl, chl_funct)
4. purrr:::as_mapper.default(.f, ...)
5. rlang::as_function(.f)
6. rlang:::abort_coercion(x, friendly_type("function"))
【问题讨论】: