【问题标题】:Automate Dplyr's mutate function自动化 Dplyr 的 mutate 函数
【发布时间】:2021-02-04 08:47:21
【问题描述】:

在一个 dplyr 聚合中自动化 mutate 函数的最佳方法是什么。

最好在示例中进行演示。 因此,在示例的第一部分中,我将根据变量 gear 的值创建新列。但是,假设我需要自动执行此步骤以自动“迭代”gear 的所有唯一值并为每个值创建新列。

有什么办法吗?

library(tidyverse)

cr <- 
  mtcars %>% 
  group_by(gear) %>% 
  nest()


# This is 'by-hand' approach of what I would like to do - How to automate it? E.g. we do not know all values of 'carb'

cr$data[[1]] %>% 
  mutate(VARIABLE1 = 
           case_when(carb == 1 ~ hp/mpg,
                          TRUE ~ 0)) %>%
  mutate(VARIABLE2 = 
          case_when(carb == 2 ~ hp/mpg,
                         TRUE ~ 0)) %>%
  mutate(VARIABLE4 =
          case_when(carb == 4 ~ hp/mpg,
                         TRUE ~ 0))

# This is a pseodu-idea of what I need to do. Is the any way how to change iteration number in ONE dplyr code?

vals <- cr$data[[1]] %>% pull(carb) %>% sort %>% unique()

for (i in vals) {
  message(i)

cr$data[[1]] %>% 
  mutate(paste('VARIABLE', i, sep = '') =  case_when(carb == i ~ hp/mpg, # At this line, all i shall be first element of vals
                          TRUE ~ 0)) %>% 
  mutate(paste('VARIABLE', i, sep = '') =  case_when(carb == i ~ hp/mpg, # At this line, all i shall be second element of vals
                          TRUE ~ 0)) %>% 
  mutate(paste('VARIABLE', i, sep = '') =  case_when(carb == i ~ hp/mpg, # At this line, all i shall be third element of vals
                                                            TRUE ~ 0))
}

【问题讨论】:

    标签: r for-loop dplyr tidyverse purrr


    【解决方案1】:

    这听起来很像所谓的“XY 问题”。

    https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem

    请阅读 tidy data 和/或 tidyr 的 pivot_longer/pivot_wider。列名不应编码信息。

    【讨论】:

      【解决方案2】:

      一种方法是使用包fastDummies中的dummy_cols

      一次只处理一个数据帧:

      cr$data[[1]] %>%
        dummy_cols(select_columns = 'carb')%>%
        mutate_at(vars(starts_with('carb_')),funs(.*hp/mpg))
      

      您也可以先执行此操作,然后按齿轮分组,因为您在计算中没有使用齿轮值,所以没关系。为此:

      cr_new=mtcars %>%
        dummy_cols(select_columns = 'carb')%>%
        mutate_at(vars(starts_with('carb_')),funs(.*hp/mpg))%>%
        group_by(gear)%>%
        nest()
      

      【讨论】:

        【解决方案3】:

        也许,这样的事情会有所帮助 -

        library(dplyr)
        library(purrr)
        
        bind_cols(mtcars, map_dfc(unique(mtcars$carb), 
         ~mtcars %>%
             transmute(!!paste0('carb', .x) := case_when(carb == 1 ~ hp/mpg,TRUE ~ 0))))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-04-23
          • 1970-01-01
          • 1970-01-01
          • 2015-02-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多