0

I would like to open an Excel file in directory "dld" that starts with "RPT". I've tried the below, but I keep getting an error:

Error in file(file, "rt") : invalid 'description' argument

I'm guessing it has something to do with the code coming from a read.csv and I'm trying to adapt it to read.table.

dld <- "C:/Users/Me/Downloads/"
filename <- paste(dld, "RPT_", sep = "")
file <- read.table(dir(dirname(filename), full.names=T, pattern=paste("^", basename(filename), sep="")))

Ideas? Any direction/help would be greatly appreciated.

stevenjoe
  • 329
  • 1
  • 4
  • 16
  • When you say Excel file, do you mean .xls or .xlsx? Or do you just mean a .csv that happens to have been saved from Excel? – joran Nov 17 '15 at 20:53
  • @joran .xlsx, thanks! – stevenjoe Nov 17 '15 at 20:56
  • In that case you'll want to use a package like **readxl**, **XLConnect** or **xlsx** that are specifically for reading that file format. – joran Nov 17 '15 at 20:57

1 Answers1

1

First, as @joran mentioned, there are several tools for reading .xlsx or xls files directly (all of which are covered here).

As to your question of finding a partially matched file name, I would use grepl as follows:

#get all file names in the directory
flz <- list.files("C:/Users/Me/Downloads/")
#find those that start with RPT (or otherwise match your pattern)
my_excel <- flz[grepl("^RPT", flz)]
#(make sure here that you've identified a unique file)

Finally, read the file:

library(readxl)
read_excel(my_excel) #(specifying whichever options as needed)
Community
  • 1
  • 1
MichaelChirico
  • 33,841
  • 14
  • 113
  • 198
  • You may want to consider what to do if there are multiple filenames that start with RPT_. – ddunn801 Nov 17 '15 at 21:45
  • 1
    @user2747404 that's why I left `my_excel` as its own line instead of combining with `read_excel`. A user should examine `my_excel` before proceeding & decide what adjustments need be made to the regex (if any). – MichaelChirico Nov 17 '15 at 21:56