Yosher
Yosher

Reputation: 805

Error related to Excel importing using read_excel

I'm new to R and studying how read_excel() and excel_sheets() work, trying to use two such codes below. These are intended to read the second sheet of an excel file.

output <- read_excel(excel_sheets("population.xlsx")[2], 
            path = "population.xlsx")

output <- read_excel(excel_sheets("population.xlsx"), 
         sheet = 2, path = "population.xlsx")

The first code runs successfully, but the second one doesn't with the error

Error: length(x) == 1L is not TRUE

I'd like to know the reason why it happens and how I can fix it.

The document of read_excel says it can use 'sheet' argument to select which sheet to read, which I guess is identical to stating the number of the order of a character vector ( i.e. excel_sheets("population.xlsx")[2] in this case).

Upvotes: 0

Views: 824

Answers (1)

Calum You
Calum You

Reputation: 15072

Just read_excel(path = "population.xlsx", sheet = 2) should work. Your first code is getting a list of all sheets and then selecting the name of the second; read_excel accepts both integer position and sheet names as the argument for sheet.

You may be confused because you need to know something about argument matching; named arguments are matched and then they are matched left to right. So in the first example, path is specified, and then the excel_sheets call is passed to the sheet argument. In the second, you specify sheet and so I think it will get passed to the range argument, which is supposed to only accept a character vector of length 1. That's the source of the error you have.

Upvotes: 2

Related Questions