【问题标题】:purrr map: How to use nested tibble column as function argumentpurrr map:如何使用嵌套的 tibble 列作为函数参数
【发布时间】:2020-11-04 00:49:10
【问题描述】:

我有点难以理解如何将列从嵌套的 tibble 传递到函数参数。例如,以下代码返回按“am”分组的“cyl”的平均值:

test <- mtcars %>% 
  group_by(am) %>% 
  nest()

get_mean <- function (df) {
  return (mean(df$cyl))
}

test <- test %>% 
  mutate(mean = map_dbl(data, get_mean))

但是我想要 cyl 以外的列的平均值,并希望将其作为参数传递给函数?我知道这是错误的代码,但我会尝试编写如下代码:

test <- mtcars %>% 
  group_by(am) %>% 
  nest()

get_mean <- function (df, column) {
  return (mean(df${{column}}))
}

test <- test %>% 
  mutate(mean = map_dbl(data, get_mean, column))

对此的任何帮助将不胜感激。我如何将column 输入到地图函数中,我应该如何编写df${{column}}

【问题讨论】:

    标签: r tidyverse purrr


    【解决方案1】:

    这应该做你想做的事。您可以使用 [[]] 运算符而不是 $ 使用变量中的字符串从数据帧中动态提取列。

    library(purrr)
    library(dplyr)
    library(tidyr)
    
    nest_data <- mtcars %>% 
      group_by(am) %>% 
      nest()
    
    get_mean <- function (df, column) {
      return (mean(df[[column]]))
    }
    
    test_cyl <- nest_data %>% 
      mutate(mean = map_dbl(data, get_mean, "cyl"))
        
    test_mpg <- nest_data %>% 
      mutate(mean = map_dbl(data, get_mean, "mpg"))
    

    【讨论】:

      【解决方案2】:

      您可以使用以下 -

      library(dplyr)
      library(purrr)
      
      get_mean <- function (df, column) {
        df %>%
          select(-{{column}}) %>%
          unlist %>% mean
      }
      
      test %>%  ungroup %>% mutate(mean = map_dbl(data, get_mean, cyl))
      
      #     am data                mean
      #  <dbl> <list>             <dbl>
      #1     1 <tibble [13 × 10]>  36.3
      #2     0 <tibble [19 × 10]>  55.5
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-01
        • 2021-07-28
        • 2016-03-10
        相关资源
        最近更新 更多