How to use setwd() In R Language

Since the sample.csv file is located in C:\Users\harsh\Desktop\w3wiki directory, hence we need to move to this directory. In R, we can move from the current working directory to any other directory using the setwd() function:

R




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


Output:

Hence, we are able to read the sample.csv file now.

How to Fix in R: error in file(file, “rt”) : cannot open the connection

In this article, we are going to see how to fix the error in file(file, “rt”) : cannot open the connection. When error that one may face in R is:

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

The R compiler produces such an error when one tries to read a CSV file but the file or the directory that is being accessed does not exist.

Similar Reads

When this error might occur in R

Let’s consider that we have a CSV file: Sample and we want to read it:...

How to Fix the Error

...

Method 1: Using setwd()

To get the current working directory in which we are in, we can use the getwd() function in R:...

Method 2: Using read.csv()

...