Tuesday, September 22, 2015

How do I know a file exists (in R programming)?

If you access the help file on your computer on which you installed R then you can find the information at this link here:

http://127.0.0.1:12506/library/base/html/list.files.html

File information can be found here:
http://127.0.0.1:12506/library/base/html/file.info.html

I had a file names.csv (I had mistaken about its extension being .CSV, it was actually names.xls.csv) which I wanted to know if it exists. Then I used the following commands:

> file.exists("C:/")                Does C:\ folder exists (you should not use the backward slash)?
[1] TRUE

> file.exists("C:/eula.3082")  I know eula.3082 exists but... The reason is perhaps permissions
[1] FALSE

> file.exists("C:/inetpub")     Does C:\inetpub exist?
[1] TRUE

> file.exists("C:/USERS")       Does C:\Users exist?
[1] TRUE

> file.exists("C:/USERS/names.csv")  Does C:\Users\names.csv exist?
[1] FALSE
oops!
> file.exists("C:/USERS/JFA.jpg")       Does C\USERS/JFA.jpg exist?
[1] TRUE

I created a CSV file in EXCEL and made sure it was saved as a CSV by opening it in Notepad.

> file.exists("C:/USERS/mysorian/Documents/names2.csv")  Does C:\USERS\names2.csv?
[1] TRUE

> file.info("C:/USERS/mysorian/Documents/names2.csv")   Provide info on the file C:/USERS/mysorian/Documents/names2.csv
                                       size isdir mode               mtime               ctime
C:/USERS/mysorian/Documents/names2.csv   98 FALSE  666 2015-09-22 16:42:20 2015-09-22 16:42:20
                                                     atime exe
C:/USERS/mysorian/Documents/names2.csv 2015-09-22 16:42:20  no

Listing files in a directory

Also,  if you know the directory you can list all the files as in the following:
--------
Error: could not find function "List.files"  -- R language is case sensitive
> list.files("C:/USERS/mysorian/documents") List the files in the directory in quotes

  [1] "__VSDeploymentFailure__.txt"                     
  [2] "~$ADI_gREETINGS.dotx"                            
  [3] "~$TrustRelated.xlsx"                             
  [4] "04092013 ConsolidatedDetails.xls"                
  [5] "3rd beneficiary details_sept15_2014.dotx"        
  [6] "4mysorian.xlsx"                                  
  [7] "Advanced SQL TOP.dot"                            
  [8] "AdvisoryMichiko.xlsx"                            
  [9] "AdvWksCustomer.rdl"                              
 [10] "Allow connections to this computer.pdf"          
 [11] "Ameritrade2014.csv"                              
 [12] "ApnStub.exe"                                     
 [13] "ArcGIS Explorer"  

No comments: