我正在尝试创建一个包来从多米尼加共和国中央银行网页下载、导入和清理数据。我已经在 Rstudio.cloud 中完成了所有编码,一切正常,但是当我在本地机器上尝试这些功能时,它们不起作用。
在对每个功能进行了深入研究后,我意识到问题在于下载的文件,它已损坏。
我包括一个函数的第一步只是为了说明我的问题。
file url
# Packages
library(readxl)
# file url.
url <- paste0("https://cdn.bancentral.gov.do/documents/",
"estadisticas/precios/documents/",
"ipc_base_2010.xls?v=1570116997757")
# termporary path
file_path <- tempfile(pattern = "", fileext = ".xls")
# downloading
download.file(url, file_path, quiet = TRUE)
# reading the file
ipc_general <- readxl::read_excel(
file_path,
sheet = 1,
col_names = FALSE,
skip = 7
)
Error:
filepath: C:\Users\Johan Rosa\AppData\Local\Temp\RtmpQ1rOT3\2a74778a1a64.xls
libxls error: Unable to open file
我正在使用临时文件,但这不是问题,您可以尝试将文件下载到您的工作目录中,但问题仍然存在。
我想知道:
顺便说一下,我使用的是 Windows 10
编辑
回答:
1- Rstudio.cloud 运行在 linux 上,但对于 Windows,我需要对
download.file()
做一些调整命令。2-
download.file(url, file_path, quiet = TRUE, mode = "wb")
这就是我一直在寻找的。
现在我有一个不同的问题。我必须想办法检测该函数是在 Linux 还是 Windows 上运行,以相应地设置该参数。
我可以使用
if
编写一个新的下载文件函数else
调用 .Platform$OS.type 结果。或者,我可以为所有 download.file() 调用设置 mode = "wb"吗?
你有什么建议?
最佳答案
来自 download.file()
的文档
The choice of binary transfer (mode = "wb" or "ab") is important on Windows, since unlike Unix-alikes it does distinguish between text and binary files and for text transfers changes \n line endings to \r\n (aka CRLF).
Code written to download binary files must use mode = "wb" (or "ab"), but the problems incurred by a text transfer will only be seen on Windows.
来源
download.file
head(print(download.file),12)
1 function (url, destfile, method, quiet = FALSE, mode = "w", cacheOK = TRUE,
2 extra = getOption("download.file.extra"), headers = NULL,
3 ...)
4 {
5 destfile
6 method <- if (missing(method))
7 getOption("download.file.method", default = "auto")
8 else match.arg(method, c("auto", "internal", "wininet", "libcurl",
9 "wget", "curl", "lynx"))
10 if (missing(mode) && length(grep("\\\\.(gz|bz2|xz|tgz|zip|rd[as]|RData)$",
11 URLdecode(url))))
12 mode <- "wb"
因此,查看源代码,如果您没有设置模式,该函数会自动使用“w”,除了 URL 包含 gz、bz2、xz 等(这就是您得到第一个错误的原因)。
以我的拙见,我认为在类 Unix 系统(例如 Linux)中,“w”和“wb”是相同的,因为它们不区分文本文件和二进制文件,但 Windows 可以。
所以你可以为所有的download.file 调用设置mode="wd"(只要它不是Windows 下的文本传输),这不会影响Linux 中的功能。
关于r - download.file() 下载损坏的 xls,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61151319/