作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 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'))
}
或者用purrr
的walk2
函数:
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
并不重要,因为您不关心此步骤后返回的内容。
注意我还出于习惯将 paste0
和 write.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/
我正在尝试将 View 的背景设置为具有从 Palette api 生成颜色的渐变 渐变将从纯色逐渐淡出,但我希望纯色部分占据大部分背景。现在它开始稳定,然后在 View 宽度上逐渐淡出,我希望它从
我是一名优秀的程序员,十分优秀!