gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:16:13 26 4
gpt4 key购买 nike

我有一个 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() 不处理这些或其他东西。

我并没有真正的编码要求,我必须把 walk 放在管道的末端(事实上,我总是可以绕过管道),但似乎我缺少一些基本的东西,这让我很烦。有什么建议吗?

最佳答案

我认为您根本不需要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 创建于 2018-03-13 (v0.2.0).

关于r - 将 purrr::walk2() 应用于管道末端的 data.frames 的 data.frame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49265737/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com