Error in openning a file in R with two different method - r

I have trouble opening a file in R with the following for loop :
#Counting the number of files in the folder
num_files <- length(list.files("C:/Users/Jane/Downloads/WantedFolder"))
num_files
#File extraction from the folder
a<-list.files("C:/Users/Jane/Downloads/Folder")
for (i in 1:num_files){
g<-a[i]
data1<-read.table(g)
head(data1)
}
To me it should be working as the classic read.table :
data1<-read.table("C:/Users/Jane/Downloads/WantedFolder/WantedFile.txt")
I got the following error and don't understand why since I've checked the directory several times and it is working for the "classic" read.table
Warning in file(file, "rt") :
cannot open file 'WantedFile.txt': No such file or directory
Error in file(file, "rt") : cannot open the connection
What is wrong ?

It depends on your working directory, which you can check using getwd(). list.files only returns the names of the files in a folder, not their full path. Based on the error, it seems like you are trying to open a file called "wantedfile.txt" in your current working directory. To avoid R assuming your current working directory, you can specify the absolute path like so:
path <- "C:/Users/Jane/Downloads/Folder"
a <- list.files(path)
a <- file.path(path, a)
This pastes the absolute path of the wanted folder to the file names returned by list.files-

Related

loading a .csv file to R

I am learning R but I am stuck in loading my own dataset into R. So far, the code that I have is the following. The dataset (.csv) is located in my desktop.
Data500 <- read.csv("sp500.csv", header = TRUE)
I get this error message in the console.
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
cannot open file 'sp500.csv': No such file or directory
This is because the file isn't located in your working directory, which is where R is searching.
use getwd() to see what working directory you are in currently (for this R session).
You can either
a) move your csv file to that working directory (if it happens to be a good place to keep it),
b) specify the full path (e.g., read.csv("C:/Users/DChavez/Documents/Project_Name/sp500.csv"))
OR
c) you can change the working directory to be where your file is before running read.csv().
Two ways to do this:
Use setwd() at the top of your code to set the working directory. In Windows, it might look something like this: setwd("C:/Users/DChavez/Documents/Project_Name/")
IF you are using RStudio, you can navigate to the "Session" bar at the top, then "Set Working Directory" then "Choose Directory...", where you will navigate to the folder that houses your csv file.

importing a CSV file

I just started learning R which is my first programming language. I tried importing a CSV file from my system which is on my downloads in my computer using:
getwd()
setwd("/downloads")
statesInfo <- read.csv('stateData.csv')
But i keep getting the error message below.
setwd("/downloads")
Error in setwd("/downloads") : cannot change working directory
statesInfo <- read.csv('stateData.csv')
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
cannot open file 'stateData.csv': No such file or directory.
Could I be getting it wrong.
R is unable to recognize the directory that you're referring to and that's why you get the first error.
The working directory remains unchanged and R can not find the file stateData.csv in the current working directory which results in the second error message.
For setting a working directory use the full path instead: setwd("C:/Users/yourname/Downloads/") - notice the forward slash instead of the back-slash.
However, If you're only importing files, you do not need to change your working directory every time. You can simply refer to files in other locations. If you're using windows - you will need to use ./ for sub-folders and ../ for folders that are one level up. For example. if your working directory is set to 'C:/Users/yourname/Desktop/R' and you want to read a file from the 'Downloads' folder, simply use the below code:
dat <- read.csv("../../Downloads/stateData.csv")
the first ../ takes you one level up to the 'Desktop' and the second ../ takes you to 'Users'. From there you are referring to 'Downloads' folder where the stateData.csv file is located.
EDIT
The above works for Windows isntallations, for Mac/others you would have to use the tilda notation: e.g. ~/Desktop
So, it should be like this.
setwd("c:/mydir")
Also.
MyData <- read.csv(file="c:/mydir/TheDataIWantToReadIn.csv", header=TRUE, sep=",")

Error while reading csv file

I have a xlsx file and to read from Rstudio i saved it as .csv file. Now when i try to read the file from Rstudio, receiving the below error.
setwd("D:/DATA SCIENCE/CCPP-Linear regression")
ccpp<- read.csv("Folds5x2_pp.csv", header = TRUE)
Error in file(file, "rt") : cannot open the connection In addition:
Warning message: In file(file, "rt") : cannot open file
'Folds5x2_pp.csv': No such file or directory
As already mentioned in the comments, the "cannot open the connection" part of the error message confirms that where R is looking is not where the file is.
A few things to keep in mind
use getwd() to see the current R working directory
use setwd() to change R's wd
You should use RStudio projects to organize your projects - this helps with the working directory thing
spaces in paths are difficult sometimes. Looks like you have "D:/DATA SCIENCE", that space can cause problems (you may need to escape the space like "DATA\ SCIENCE".
You can read the file using the full path (e.g. read.csv("D:/DATA SCIENCE/path/file.csv")) or if you are doing this a lot, set a variable to your path data_path ="D:/DATA SCIENCE/path/" and then read.csv(file.path(data_path, "file.csv")) where file.path concatenates with your OS specific path delimiter.
You can import files into RStudio using the Import Dataset option under Tools in the menu bar.

R – first time using projects – does not open csv file even if it is in working directory

I created a project in R (my first "project"; before I was just dabbling in a moltitude of files). To do that, first I created a new empty folder in Finder and named it "new_study_results_analysis_R". Then I created the new project referring to that folder. After that, I moved all the files I wanted to analyze in the aferomentioned folder.
At this point I tried to open one of the files:
> dat = read.csv("30sub8a10.csv", header = TRUE)
But I get the error:
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
cannot open file '30sub8a10.csv': No such file or directory
So I checked:
> getwd()
[1] "/Users/S/Users/S/Dropbox/(0.01)__OculusStudy/(0.0)New_study/new_study_results_analysis_R"
The working directory is the right one.
I don't understand. How can I open the files?
There's a duplicate "/Users/S/" in the getwd() output. To set the right working directory in a Mac, open up a terminal console, and drag and drop the folder with the data into terminal. Copy the path that appears in terminal and use that in setwd("...").

list.files error (easy?) [R]

Im trying to r.bind all files in certain directory with the following code in R (all files are formatted the same way):
gene_list <- list.files("/nethome/genelist/")
gene_CH <- do.call("rbind",lapply(gene_list, FUN=function(files)
{read.table(files, header=TRUE, sep="\t", stringsAsFactors=FALSE)}))
write.table(gene_CH,"/nethome/genelist/all.genes.CH_v2t.txt",sep="\t",quote=F,row.names=F)
However, I get the following error:
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
cannot open file 'A2ML1_v2t.txt': No such file or directory
Thing is, A2ML1_v2t.txt is in the directory. Also, what is more puzzling (to me anyway) is that this code worked this morning. But for some reason, its not working now.
Any suggestions?
Two possibilities:
This morning, your working directory was /nethome/genelist/, but now, it isn't. list.files() only gives filenames, not absolute paths, so your second line will search through the current working directory. Try getwd() to check and setwd() to change it.
You do have read permission in the directory, do you?

Resources