将 purrr::walk2() 应用于管道末端的 data.frame 中的 data.frames

Applying purrr::walk2() to a data.frame of data.frames at the end of a pipe

我有一个 R 数据框,有一列数据框,我想将每个数据框打印到一个文件中:

df0 <- tibble(x = 1:3, y = rnorm(3))
df1 <- tibble(x = 1:3, y = rnorm(3))
df2 <- tibble(x = 1:3, y = rnorm(3))

animalFrames <- tibble(animals = c('sheep', 'cow', 'horse'),
                       frames = list(df0, df1, df2))

我可以用 for 循环来做到这一点:

for (i in 1:dim(animalFrames)[1]){
    write.csv(animalFrames[i,2][[1]], file = paste0('test_', animalFrames[i,1], '.csv'))
}

或使用purrrwalk2函数:

walk2(animalFrames$animals, animalFrames$frames,  ~write.csv(.y, file
= paste0('test_', .x, '.csv')))

有什么方法可以把这个 walk 函数放在 magrittr 管道的末尾?

我在想:

animalFrames %>% do({walk2(.$animals, .$frames, ~write.csv(.y, file = paste0('test_', .x, '.csv')))})

但这给了我一个错误:

Error: Result must be a data frame, not character
Traceback:

1. animalFrames %>% do({
 .     walk2(.$animals, .$frames, ~write.csv(.y, file = paste0("test_", 
 .         .x, ".csv")))
 . })
2. withVisible(eval(quote(`_fseq`(`_lhs`)), env, env))
3. eval(quote(`_fseq`(`_lhs`)), env, env)
4. eval(quote(`_fseq`(`_lhs`)), env, env)
5. `_fseq`(`_lhs`)
6. freduce(value, `_function_list`)
7. withVisible(function_list[[k]](value))
8. function_list[[k]](value)
9. do(., {
 .     walk2(.$animals, .$frames, ~write.csv(.y, file = paste0("test_", 
 .         .x, ".csv")))
 . })
10. do.data.frame(., {
  .     walk2(.$animals, .$frames, ~write.csv(.y, file = paste0("test_", 
  .         .x, ".csv")))
  . })
11. bad("Result must be a data frame, not {fmt_classes(out)}")
12. glubort(NULL, ..., .envir = parent.frame())
13. .abort(text)

大概是因为 write.csv() 正在返回数据帧,而 do() 不处理这些或其他东西。

我并没有真正的编码要求,我必须在管道的末端放置步行(事实上,我总是可以绕过管道),但似乎我遗漏了一些基本的东西,这是窃听我。 有什么建议吗?

我认为您根本不需要 do。以下两项都适合我。第一个与我认为的减去 do 完全相同,第二个使用 magrittr 方便的 %$% 运算符将列名公开给 walk2 并避免.$。请注意,如果这是在管道的末尾,那么使用 walk2 还是 map2 并不重要,因为您不关心此步骤后返回的内容。

注意我也出于习惯将 paste0write.csv 换成了 tidyverse 等价物,但它们很容易放回去。

library(tidyverse)
df0 <- tibble(x = 1:3, y = rnorm(3))
df1 <- tibble(x = 1:3, y = rnorm(3))
df2 <- tibble(x = 1:3, y = rnorm(3))

animalFrames <- tibble(animals = c('sheep', 'cow', 'horse'),
                       frames = list(df0, df1, df2))

animalFrames %>%
  walk2(
    .x = .$animals,
    .y = .$frames,
    .f = ~ write_csv(.y, str_c("test_", .x, ".csv"))
  )

library(magrittr)
#> 
#> Attaching package: 'magrittr'
#> The following object is masked from 'package:purrr':
#> 
#>     set_names
#> The following object is masked from 'package:tidyr':
#> 
#>     extract
animalFrames %$%
  walk2(
    .x = animals,
    .y = frames,
    .f = ~ write_csv(.y, str_c("test_", .x, ".csv"))
  )

reprex package (v0.2.0) 创建于 2018-03-13。