1

I'm trying to read in a csv file from a folder containing all csv files and having difficulty. So far I have changed my path, set my working directory and have identified all files as CSV in the working directory. When I run this line I get:

Error in file(file, "rt") : cannot open the connection In addition: Warning message: In file(file, "rt") : cannot open file '^GSPC.csv': No such file or directory .

I was wondering if anyone could please help. Thank you.

dir.data = "C:/Users/rileylong/desktop/Stocks/
setwd(dir.data)
listcsv <- dir(pattern = "*.csv")
data <- read.csv("^GSPC.csv", stringsAsFactors = FALSE)[,c(1,5)]
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
rilo
  • 11
  • 1
  • 2
  • 1
    you probably need `do.call(rbind, lapply(listcsv, read.csv, stringsAsFactors = FALSE))` – Ronak Shah Jun 25 '19 at 02:51
  • 1
    you're missing a `"` after the / in the first line – morgan121 Jun 25 '19 at 02:58
  • 1
    also, might be worth using `read_csv()` from `library(tidyverse)` - certain advantages over `read.csv()`, eg I think faster on large files – dbo Jun 25 '19 at 03:29
  • I just want some clarity are you trying to use the caret for regex. If you are, I'm not sure you can use `read.csv` like this. It would be better practice to use regex on the list of files in the directory to subset then just use each element as the argument to `read.csv`. – John Siryj Jun 25 '19 at 02:58

1 Answers1

0

You could try to put the entire directory in read.csv function. Like this:

data <- read.csv("C:/Users/rileylong/desktop/Stocks/GSPC.csv", stringsAsFactors = FALSE)

data_new = data[,c(1,5)]
vpz
  • 984
  • 1
  • 15
  • 26