在 R "'path' must be a string"中使用 readxl 读取 xlsx 文件时出错



我只是试图从R中的一个路径使用excel文件,尽管我的代码看起来是正确的,并且与readxl示例一致,但我仍然会遇到同样的错误。

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

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

更新1/21:我已经开始了,只是依赖于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)。所以我显然不能用路径的名字,我不知道该怎么做。

好吧,你把R"语法;一点点。让我们把它分成2:

1( 使用read_xlsx

我在你的代码中添加了一些注释,以澄清问题

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. 

你可以在这里阅读更多关于如何创建函数的

最新更新