【问题标题】:Error from reading an xlsx file using readxl in R "'path' must be a string"在 R 中使用 readxl 读取 xlsx 文件时出错“'path' must be a string”
【发布时间】:2022-01-04 14:29:56
【问题描述】:

我只是尝试使用 R 中路径中的 excel 文件,即使我的代码看起来正确并且与 readxl 示例一致,我仍然遇到相同的错误。

data <- read_xlsx("/Users/......../filename.xlsx")
read_xlsx(data)
> Error: `path` must be a string

我避免安装 xlsx 包,因为我没有一堆 Java 依赖项,这似乎更容易。

21 年 1 月 5 日更新:我继续前进,只是依靠 read_xlsx("my/path/to/file.xlsx")。我正在尝试对这个文件应用一个函数,所以现在当我像这样使用路径作为它的名称时:my_function = function("my/path/to/file.xlsx", a, b, c) 等它不起作用,我收到这个错误:Error: unexpected string constant in "my_function = function("my/path/to/file.xlsx", a, b, c)。所以我显然不能使用路径作为它的名称,我不知道该怎么做。

【问题讨论】:

  • 您只需要使用一次read_xlsx() 将 excel 文件导入 R。如果可行(检查您的环境以查看 data 对象是否存在,或者只需运行 data 即可看看返回了什么),然后你就可以走了。
  • 如果我想在每次运行其余代码时从一个驱动器中提取此 excel 文件的更新版本,这会起作用吗? (其余代码是在共享 excel 文件上经常使用的函数)。我想如果我导入它,那么文件将不会更新。
  • 如果对 excel 文件进行了更改(并保存),下次运行 read_xlsx("my/path/to/file.xlsx") 时,它将使用更新的版本。
  • 谢谢,这很有帮助。那么当我需要在代码中引用文件时,我使用该路径序列作为其名称?
  • 是的 - 这是正确的。

标签: r readxl


【解决方案1】:

好吧,你有点搞砸了 R“语法”。让我们把它分成2个:

1) 使用read_xlsx:

我在您的代码中添加了一些 cmets 以澄清问题

data <- read_xlsx("/Users/......../filename.xlsx") # This is reading your file into a variable called "data"
read_xlsx(data) #<-- So this line doesn't make sense, because you are trying to read an excel file, but the path of the excel file is what you already uploaded.

换句话说,你不需要第二行

所以要解决您的代码,请更改为:

data <- read_xlsx("/Users/......../filename.xlsx")

data

2) 尝试构建函数

你又把语法搞砸了。 创建函数时,它应该适用于所有情况。因此,您应该编写“路径”,而不是定义要上传的特定文件,然后在使用该功能时,将“路径”替换为您的路径。 所以:

# First define a function for "path", "a", "b" and "c"
my_function = function(path, a, b, c){
data = read_xlsx(path)
data
}

# And now to use the function:
filepath = "/Users/......../filename.xlsx" # This defines a string variable that you can feed to your function
my_function(filepath, a, b, c) # This runs the function on that string variable and the other variables: a, b, c. 

你可以阅读更多关于如何创建函数here

【讨论】:

    猜你喜欢
    • 2016-10-10
    • 1970-01-01
    • 2013-09-22
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    相关资源
    最近更新 更多