【问题标题】:purrr::map does not work with pipe operatorpurrr::map 不适用于管道运算符
【发布时间】:2021-07-23 04:52:27
【问题描述】:

我有一个这样的数据框:

df <- tibble(
  i = rep(1:10, times = 5),
  t = rep(1:5, each = 10)
  ) %>% 
  mutate(y = rnorm(50))

我想应用一个函数,将每个 t 的数据框作为参数:

f <- function(df){
  return(lm(y ~ +1, data = df))
}

当我使用管道运算符为嵌套数据框应用 purrr::map 时,出现错误。

# does not work
df_nested <- df  %>% 
  nest(data = c(t, y)) %>% 
  rename(data_col = data) 

df_nested %>% 
  purrr::map(.x = .$data_col, .f = f)

另一方面,当我不使用管道运算符时,我得到了想要的结果。

# Ok
purrr::map(.x = df_nested$data_col, .f = f)

据我了解,两个代码都应该返回相同的结果。管道运算符的代码有什么问题?

【问题讨论】:

    标签: r tidyverse purrr


    【解决方案1】:

    Pipe 已经将先前的值 (df_nested) 作为第一个参数传递给 map。您可以使用{} 来阻止这种情况发生。

    library(tidyverse)
    
    df_nested %>% 
      {purrr::map(.x = .$data_col, .f = f)}
    

    另一种方法是使用 -

    df  %>% 
      nest(data_col = c(t, y)) %>%
      mutate(model = map(data_col, f))
    
    #      i data_col         model 
    #   <int> <list>           <list>
    # 1     1 <tibble [5 × 2]> <lm>  
    # 2     2 <tibble [5 × 2]> <lm>  
    # 3     3 <tibble [5 × 2]> <lm>  
    # 4     4 <tibble [5 × 2]> <lm>  
    # 5     5 <tibble [5 × 2]> <lm>  
    # 6     6 <tibble [5 × 2]> <lm>  
    # 7     7 <tibble [5 × 2]> <lm>  
    # 8     8 <tibble [5 × 2]> <lm>  
    # 9     9 <tibble [5 × 2]> <lm>  
    #10    10 <tibble [5 × 2]> <lm>  
    

    【讨论】:

      猜你喜欢
      • 2018-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-04
      • 1970-01-01
      • 2022-06-29
      相关资源
      最近更新 更多