为什么 purrr::pwalk 在写入 CSV 文件时不起作用

问题描述 投票:0回答:1

我正在尝试将模拟测试数据写入临时目录。我将不得不编写大量文件,并且我想使用

purrr
包中的函数编写循环,因为这些似乎具有简洁的设计语法。但我无法让
purrr::pwalk
工作?我做错了什么?

library(data.table)
library(purrr)

# define temporary directory
pp <- withr::local_tempdir()

# define function to write simulated files
f <-
  function(.x,.y) {
    dt <- data.table(country = .x, school_id = 1:2, school_type = c("a","b"))
    fwrite(dt, local_tempfile(pattern = paste0("school.",.x), tmpdir = .y))
  }
# deploy function to write two files
purrr::walk2(.x = c("at","de"), .y = pp, .f = f)

# why no files in pp?
list.files(pp)

我参考了这些:

https://www.tidyverse.org/blog/2023/05/purrr-walk-this-way/

https://adv-r.hadley.nz/functions.html?q=purrr#purrr-style

r purrr temporary-files
1个回答
0
投票

tempdir
中没有
data.table:fwrite()
参数。
withr::local_tempfile
为我们提供了完整路径,而不仅仅是文件名。因此,该函数按预期工作,它只是写入另一个临时文件夹(由
local_tempfile
创建,而不是您分配的
pp

library(data.table)
library(purrr)

pp <- withr::local_tempdir()

fw <- function(.x, .y) {
    dt <- data.table(country = .x, school_id = 1:2, school_type = c("a","b"))
    fwrite(dt, paste(.y, paste0("school.", .x), sep = "/"))
  }

purrr::walk2(.x = c("a","b"), .y = pp, .f = fw)

list.files(pp)
#> [1] "school.a" "school.b"

创建于 2024-02-15,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.