Reputation: 1021
I have multiple csv files that are within one folder. Each csv file contains a table of 200 rows and 200 columns. I can bring in each file individually and display it as an matrix. I can also do a dir and list each file in the folder where they are located. What I need to do is bring in each file, open them and then combine them into an array. When I do this though I get a warning that there is no such file.
my code for this is
x <- dir(path=" ", pattern = ".csv")
num <- array(0,dim=c(200,200,length(x)))
for(i in 1:length(x)){
temp <- read.csv(x[i], skip=1)
temp2 <- temp[,2]
num[,i]<-temp2
}
This gives me the warning
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
cannot open file 'test_1.csv': No such file or directory
Again, when I am working with individual files I can import them just fine and and list them and open them as a matrix. Why am I getting this warning? Why is R able to find my file when I do one at a time but not for multiple at a time?
Upvotes: 3
Views: 2046
Reputation: 468
First are you sure you are reading the list of files into the variable x
properly. I think there are some issues with your for loop. Also are you sure you are in the same directory as those files? In the dir
command you enter " "
for the path
variable, I am not sure what that means. Try this
> x <- dir(pattern = ".csv")
> num <- array(0,dim=c(200,200,length(x))) # in my case `length(x)` is 9.
> m <- matrix(rnorm(200*200),nrow=200,ncol=200) # generate some 200x200 matrix
> for(i in 1:length(x)){
num[,,i] <- m # notice its num[,,i] and not num[,i]
}
> num[1:4,1:4,9]
[,1] [,2] [,3] [,4]
[1,] -1.5674073 0.05364477 0.8367233 1.7995047
[2,] -0.8613244 1.00400787 -0.2464169 -1.2897856
[3,] -0.7907845 -1.40617992 1.0596680 -0.5270983
[4,] -0.5206049 0.66253519 1.6820722 1.2017410
Upvotes: 2