File not present error when path of read_xlsx is created with str_c

Asked 2 years ago, Updated 2 years ago, 74 views

Create the beginning of the file save path with stringr::str_c.

DirectoryName<- "D1"
SavePath<-str_c("data/directory/", DirectoryName, sep=", collapse=NULL)

When I try to open an Excel file with readxl::read_xlsx using this SavePath, I get an error.

read_xlsx(str_c(SavePath, "TargetExcel.xlsx", sep="", collapse=NULL), sheet="sheet_name")

The error message is

Error: Unable to open the Evaluation error: zip file 'data/code ··200202001.xlsx'

That's it.

In this regard, if str_c is set to base::paste0, Excel will be opened successfully.The file path contains Japanese.

Please let me know if you know why you can't open it with str_c, but with paste0.

r tidyverse

2022-09-30 21:48

1 Answers

I'm a questioner.
SavePath's own character code is processed by UTF-8 on R, and if shift-jis is mixed here, the path appears to be garbled internally, causing an error.
The solution is to use iconv to convert from utf-8 to shift-jis.

DirectoryName<- "D1"
SavePath<-str_c("data/directory/", DirectoryName, sep=", collapse=NULL)
SavePath<-iconv(SavePath, from="utf-8", to="cp932")

as

read_xlsx(
    iconv(
        str_c(SavePath, "TargetExcel.xlsx", sep="", collapse=NULL),
        from = "uft-8", to = "cp932")
    ),
    sheet="sheet_name")

Then it was resolved.
I think it's probably because I use R on Windows.
The last sheet_name part may also be transformed into shift-jis in some cases, as it may be a mixture of character codes.
Paste0 solves this ambiguity, but stringr::str_c is strictly designed to use utf-8 and we can infer that this is what happened.

Thank you for your comment.


2022-09-30 21:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.