【问题标题】:Categorise a variable in a list using the purrr::map_df() function使用 purrr::map_df() 函数对列表中的变量进行分类
【发布时间】: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"))
  

【问题讨论】:

    标签: r tidyverse purrr


    【解决方案1】:

    首先,您应该在函数中使用矢量化版本。这可以使用ifelsecase_when 完成,如果您有更多类别使用cut 会更好。

    library(dplyr)
    
    chl_funct <- function(x) {
      
      case_when(x == 0 ~ "0 days", 
                x < 100 ~ " < 100", 
                x >= 100 & x < 150 ~ "100 - 149", 
                x >= 150 & x < 200 ~ "150 - 199",
                TRUE ~ ">= 200")
    }
    

    然后您可以将此函数应用于nhanes_imp$chl 中数据集的每一列。

    nhanes_imp$chl <- nhanes_imp$chl %>% mutate(across(.fns = chl_funct))
    

    【讨论】:

    • 这会将函数应用于所有变量
    • 是的,您要将函数应用于哪些变量?
    • chl 变量
    【解决方案2】:

    我们可以使用cut

    chl_funct <- function(x) {
          cut(x, breaks = c(-Inf, 0, 100, 150, 200, Inf), labels = c('0 days',
           "< 100", "100 - 149", "150 - 199", ">=200"))
    }
    

    然后使用

    library(dplyr)
    nhanes_imp$chl <- nhanes_imp$chl %>%
          mutate(across(everything(), chl_funct))
    

    【讨论】:

      猜你喜欢
      • 2023-02-19
      • 2020-02-03
      • 2018-07-03
      • 1970-01-01
      • 1970-01-01
      • 2021-05-05
      • 1970-01-01
      • 2020-01-01
      • 1970-01-01
      相关资源
      最近更新 更多