Error in file.choose() file choice cancelled

Hi! I do have a problem when I want to knit my .rmd file.

I always end up here:

Thats the code:

knitr::opts_chunk$set(echo = TRUE)

require(mosaic) 
require(knitr)
data <- read.csv2(file.choose(), encoding="latin1")

library(mosaic)

Then it comes up with this error in German:

Fehler in file.choose() : Dateiauswahl abgebrochen
Ruft auf: <Anonymous> ... eval -> eval -> read.csv2 -> read.table -> file.choose
Ausführung angehalten

Thanks for any help!

Hi! Welcome!

I suspect that the problem is that file.choose() needs to be used in an interactive session. When you knit your file via the Knit button in RStudio, knitr runs in its own session that is not interactive. Is there a reason you can’t supply the path to the CSV instead of using file.choose()?

(By the way, I moved this question to the #R-Markdown category because it is most likely to attract helpers with the right experience there. I also took the liberty of adding proper code formatting :sparkles: to your post — it’s difficult to read code that isn’t formatted as code. To do that yourself in the future, you can use the button in the posting box that looks like this: </> (or check out this FAQ).)

1 Like

Hi @jcblum, i am really new to RStudio so I have no idea what to do. Can you explain step by step what I should try?

Thanks

I’m happy to try! But it will help me to know a little bit more info:

  • Where are you keeping the CSV that you expect to choose with file.choose()? Is it in the same folder as your .Rmd file, or somewhere else?

  • Do you expect this code to always choose the same file?

It is in the same folder. And yes, the code should always choose the same file :slight_smile:

Thanks! Give this a try:

Replace this line:

data <- read.csv2(file.choose(), encoding="latin1")

with this one:

data <- read.csv2("name_of_your_file.csv", encoding="latin1")

That works because it’s a relative file path: since the CSV and the .Rmd are in the same folder, the path from the .Rmd to the CSV is just the name of the CSV file. It’s like telling the .Rmd, “look at the files sitting next to you and find the one called ‘name_of_your_file.csv’”.


By the way, do you know that RStudio can help you fill in file paths like this one? When you need to enter a file path, try just typing the quotes and then (with your cursor between the quotes) pressing tab — RStudio will pop up a little window that browses for nearby files and when you choose one, it inserts the correct path into your code.

We also have a great thread here with resources for people who are new to R and RStudio that you might want to check out:

2 Likes