R语言setwd无法更改工作目录问题求助:启动会话、调用plotly及安装tinytex均触发相同报错
Hey there, I know this setwd() error can be super frustrating—especially when it hits right at startup and messes up libraries like plotly or tinytex installs. Let's break down the solutions step by step:
1. First, check R's running permissions
This is the most common culprit. R might not have the rights to access or modify directories:
- Windows: Right-click R or RStudio, select "Run as administrator" and try again. Restricted user accounts often block R from changing directories.
- macOS/Linux: Open your terminal and launch R with
sudo R(you'll need your admin password). Note: Use sudo sparingly—exit R after testing to avoid unintended system changes.
2. Manually set a working directory with full access
Pick a folder you definitely have read/write permissions for (like your user Documents folder), then:
- Run this command (replace the path with your own):
setwd("C:/Users/Miquel/Documents/R_Workspace") # Windows # OR setwd("~/Documents/R_Workspace") # macOS/Linux - RStudio users can skip typing: Go to Session > Set Working Directory > Choose Directory and select your folder graphically.
3. Fix the temporary directory (tempdir()) issue for tinytex
The tinytex::install_tinytex() error happens because R can't access its default temp folder. Here's how to fix it:
- First, check where R is trying to use as temp dir:
tempdir() - Go to that folder in your system and verify you have read/write permissions. If not:
- Create a new temp folder you control (e.g.,
C:/Users/Miquel/Documents/R_Tempon Windows) - Tell R to use this folder instead:
Sys.setenv(TMPDIR = "C:/Users/Miquel/Documents/R_Temp")
- Create a new temp folder you control (e.g.,
- Now try installing tinytex again:
tinytex::install_tinytex()
4. Set a permanent default working directory
To avoid this error on every startup:
- RStudio: Go to Tools > Global Options > General, then under Default working directory, select your trusted folder. Click Apply and restart RStudio.
- Non-RStudio: Edit your
.Rprofilefile (create it if it doesn't exist) and add:
This will run automatically every time you start R.setwd("your/trusted/directory/path")
5. Fixing plotly's related error
The plotly issue is just a side effect of the same directory permission problem. Once you resolve the core setwd() issues above, try running plot_ly() again—it should work without the error.
内容的提问来源于stack exchange,提问作者Miquel




