purrr::map 不适用于管道运算符
purrr::map does not work with pipe operator
我有这样一个数据框:
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)
据我了解,两种代码应该return 产生相同的结果。管道运算符的代码有什么问题?
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>
我有这样一个数据框:
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)
据我了解,两种代码应该return 产生相同的结果。管道运算符的代码有什么问题?
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>