R语言如何修复:error in file(file, “rt”) : cannot open the connection

R语言如何修复:error in file(file, “rt”) : cannot open the connection

在这篇文章中,我们将看到如何解决file(file, “rt”)中的错误:无法打开连接。当人们在R中可能面临的错误是。

Error in file(file, "rt") : 
cannot open the connection

In addition: Warning message:
In file(file, "rt") :
 cannot open file 'sample.csv': 
 No such file or directory
Bash

当人们试图读取一个CSV文件,但被访问的文件或目录不存在时,R编译器会产生这样一个错误。

当这种错误在R中可能发生时

让我们考虑一下,我们有一个CSV文件。样本,我们想读取它。

# Try to read sample CSV file
df <- read.csv('sample.csv')
Bash

输出

R语言如何修复:error in file cannot open the connection

R编译器产生这个错误是因为在当前工作目录中没有CSV文件的名称为sample。

如何修复这个错误

为了得到我们当前的工作目录,我们可以使用R中的getwd()函数。

例子

# Print the current directory
getwd()
Bash

输出

R语言如何修复:error in file cannot open the connection

方法1:使用setwd()

由于sample.csv文件位于C:\Users\harsh\Desktop\GeeksforGeeks目录,因此我们需要移动到这个目录。在R中,我们可以使用setwd()函数从当前工作目录移动到任何其他目录。

# Mark the current directory
setwd('C:\\Users\\harsh\\Desktop\\GeeksforGeeks')
 
# Read the sample.
dataframe <- read.csv('sample.csv', header=TRUE,
                      stringsAsFactors=FALSE)
 
# view data
dataframe
Bash

输出

R语言如何修复:error in file cannot open the connection

因此,我们现在能够读取sample.csv文件。

方法2:使用read.csv()

另一种方法是通过给出文件的完整路径来访问csv文件,而不是去那个目录。

例子

# Read the CSV file by giving the complete file path
dataframe <- read.csv('C:\\Users\\harsh\\Desktop\\GeeksforGeeks\\sample.csv',
                      header=TRUE, stringsAsFactors=FALSE)
 
# Display the dataframe
dataframe
Bash

输出

R语言如何修复:error in file cannot open the connection

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册