1. 程式人生 > >R語言:“cannot open the connection”的解決辦法

R語言:“cannot open the connection”的解決辦法

在R語言的實踐中,讀入資料檔案幾乎是必須的操作,但沒有設定好工作空間的位置,將會提示如下錯誤:

Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
  cannot open file 'Salary.csv': No such file or directory

對於讀取檔案的操作來說,如果採用相對路徑的話,原因主要在於當前工作空間的指向不準確,最直接的辦法是呼叫“setwd”命令,如下:

#   設定為工作目錄
setwd("D:/Workspace/R-Works/R-Stat"
)

另外,在以指令碼方式執行R指令碼時,也儘可能顯式地指定當前工作空間,如下:

#! /usr/bin/env RScript
# 顯式地指定工作目錄
setwd("D:/Workspace/R-Works/R-Stat")
# LIST
items <- read.csv("Salary.csv", TRUE, encoding = "UTF-8")
# 
typeof(items)

如果是採用“RStudio”IDE工具,則可以點選右下角檔案面板“More->Set As Working Dictionary”,如下圖:
RStudio

其他問題

1. 最後一行未輸入換行符(回車)

Warning message:
In read
.table("Score.txt", header = TRUE, sep = ",", quote = "\"", : incomplete final line found by readTableHeader on 'Score.txt'

2. 中文字元解析失敗(或者其他格式問題,一般都是某列資料格式問題)

<0 行> (或0-長度的row.names)