Miles
Miles

Reputation: 69

Error in file(file, "rt") : cannot open the connection (looking for another solution)

I've been looking for solutions but I still can't fix it.

If you have any idea ?

My current directory is : "C:/Users/François/Desktop/CHALLENGE KAGGLE/données/google"

Here you can find my code :

            setwd("C:/Users/François/Desktop/CHALLENGE KAGGLE/données/google")
getwd ()

files_names <- list.files(path="C:/Users/François/Desktop/CHALLENGE KAGGLE/données/google")
nb_files <- length(files_names)
data_names <- vector("list",length=nb_files)

for (i in 1 : nb_files)
{
  data_names[i] <- strsplit(files_names[i], split=".csv")
}

for (i in 1:nb_files) {
  assign(data_names[[i]],
         read.csv2(paste (here("/", files_names[i])),sep=",",skip=1))
}

and the error message is : Error in file(file, "rt") : cannot open the connection

I get this error after the last loop. The first one works well.

Thanks.

Upvotes: 1

Views: 146

Answers (1)

akrun
akrun

Reputation: 886938

Instead of doing a for loop, an option is lapply and store the output in a list

lst1 <- lapply(file_names, read.csv, skip = 1)
names(lst1) <- sub("\\.csv", "", file_names)

It is better not to create multiple objects in the global environment with assign. If it is really needed

list2env(lst1, .GlobalEnv)

In the OP's code, the assignment to 'data_names' can be

data_names[[i]] <- strsplit(files_names[i], split=".csv", fixed = TRUE)[[1]]

as data_names is initialized as a list. By doing the data_names[i], it is creating a list element inside the list. Also, the output of strsplit is a list. Here, we split each 'files_names' separately, so it would be a list of length 1. We need to extract that element as a vector ([[1]])

Upvotes: 2

Related Questions