Need help manipulating directory string in a function - r

I'm having trouble getting the current the current directory of my R Shiny app. I use the getSrcDirectory function to get the script's current directory and then try to manually modify it into the appropriate format to pass to xlsx::loadWorkbook, in order to load a .xlsx file. Here is the pertinent code:
#get the directory of the script by creating an empty function.
src<-getSrcDirectory(function(x) {x})
wb <- loadWorkbook(file = c(gsub("/", "\\\\", c(src, "/www/NJ2012.xlsx")),
"\\www\\NJ2012.xlsx"))
I'm trying to get the file directory to look like this: C:\\Users\\misha\\Desktop\\Accessible Project\\R_Econ_App\\www\\NJ2012.xlsx.
My script is in a folder called R_Econ_App, so it should be included in the src variable. I concatenated an additional string to the src string to provide some more information about where certain files are in certain sub directories. I use gsub in an attempt to replace "/" with "\" because that's what the file directory passed into loadWorkbook has to look like.
Can you please help me figure out where my mistake is and how to fix it?

Don't bother with gsub. Just use file.path to join your directory and file path
loadWorkbook(file=file.path(src, "www", "NJ2012.xlsx"))

Related

excel_sheets produces: Error: `path` does not exist: ‘AE800’ but rstudio has the file saved in my environment and I can open file

I am still new to R and I am not sure if I am missing something simple. I can open the excel file in R and it displays only the first tab/sheet. I know the path exists because I have the file currently on R and I copied the path right from the "copy path" option on the document. The file is also in my set working directory. Image of rstudio below. Thank you.
I suggest this workflow instead:
path <- "C:\\Users\\spice\\......." # use your real path here
shnms <- sheet_names(path)
alldata <- lapply(shnms, function(nm) read_excel(path, sheet=nm))
and you'll get a named list, each element is a worksheet in the original workbook.

How to load jpeg picture from directory

I'm trying to load and plot a picture from that path :
C:\Users\Rayane_2\Desktop\Data\PCB-DATASET-master\PCB-DATASET-master\01_missing_hole_01.jpeg
I tried :
library(imager)
file <- system.file('C:\Users\Rayane_2\Desktop\Data\PCB-DATASET-master\PCB-DATASET-master\01_missing_hole_01.jpeg',package='imager')
im <- load.image(file)
im # file not found
Example of correct run provided by the package :
library(imager)
file <- system.file('extdata/parrots.png',package='imager')
#system.file gives the full path for a file that ships with a R package
#if you already have the full path to the file you want to load just run:
#im <- load.image("/somedirectory/myfile.png")
im <- load.image(file)
plot(im) #Parrots!
Thank you for your help !
Backslashes as directory delimiters must be escaped, you should have seen the error
Error: '\U' used without hex digits in character string starting ""C:\U"
Escape it with another backslash, as in
'C:\\Users\\Rayane_2\\Desktop\\Data\\PCB-DATASET-master\\PCB-DATASET-master\\01_missing_hole_01.jpeg'
Even on windows, though, one can use forward-slashes, so this also works:
'C:/Users/Rayane_2/Desktop/Data/PCB-DATASET-master/PCB-DATASET-master/01_missing_hole_01.jpeg'
system.file only finds files within packages. From ?system.file:
Description
Finds the full file names of files in packages etc.
Arguments
...: character vectors, specifying subdirectory and file(s) within
some package. The default, none, returns the root of the
package. Wildcards are not supported.
This means that all paths provided in the ... arguments need to be relative. One such example is what you put in your question,
system.file('extdata/parrots.png',package='imager')
If you look at the file structure of the installed package (perhaps C:/Users/Rayane_2/R/win_library/4.1/imager), you'll see directories named Meta, R, data, doc, help, html, and (not found in every package) extdata. In that directory must be parrots.png. If a file is found within the specified package's installation directory, then the full (absolute) path of the file you seek is returned.
The value of system.file is that you may not know the full path. This is a good method when (1) doing something programmatically where other users will be using your code; (2) you have multiple library paths in .libPaths() and don't know which one contains the package, and you don't want to check all of them yourself; or (3) you want shorter and more self-documenting code.
If you already know the full path of a file, then system.file doesn't help.
Bottom line, system.file is the wrong function for this.
Just load the file directly.
library(imager)
im <- load.image('C:/Users/Rayane_2/Desktop/Data/PCB-DATASET-master/PCB-DATASET-master/01_missing_hole_01.jpeg')
Use one of these.
For more info see ?Quotes, ?file.path, ?Sys.getenv, ?path.expand. The path.expand example will depend on how your home directory is set but typically it has been set to C:\Users\yourname\Documents .
file.path("C:", "Users", "Rayane_2", "Desktop", "Data", "PCB-DATASET-master",
"PCB-DATASET-master", "01_missing_hole_01.jpeg")
file.path(Sys.getenv("USERPROFILE"), "Desktop", "Data", "PCB-DATASET-master",
"PCB-DATASET-master", "01_missing_hole_01.jpeg")
r"{C:\Users\Rayane_2\Desktop\Data\PCB-DATASET-master\PCB-DATASET-master\01_missing_hole_01.jpeg}"
"C:\\Users\\Rayane_2\\Desktop\\Data\\PCB-DATASET-master\\PCB-DATASET-master\\01_missing_hole_01.jpeg"
# this depends on how your home variable has been set but the
# setting is often such that this works
path.expand("~\\..\\Desktop\\Data\\PCB-DATASET-master\\PCB-DATASET-master\\01_missing_hole_01.jpeg")
"C:/Users/Rayane_2/Desktop/Data/PCB-DATASET-master/PCB-DATASET-master/01_missing_hole_01.jpeg"
# after entering this navigate to file. This will display the path
# to the file and you can then copy and paste it from the
# R console into your code.
file.choose()

How to read an Excel file from a folder without specifying the filename?

Is there a way to read an Excel file into R directly from a folder without having to specify the filename?
I'm using the readxl library and I have only 1 file in the folder, but the file's name changes monthly.
Thanks!
The computer need to have the path anyway BUT you can get it without giving if you are absolutly sure that this is the only one file in your folder
see https://stat.ethz.ch/R-manual/R-devel/library/base/html/list.files.html
to learn more about how to open a directory and getting filename inside.
If this isn't the only file but this is the only excel file you while have to get the extension of each file and do some parsing to take a decision of wich file you want to open
As noted in other answers, this can be solved using the dir function.
Assuming the variable path contains the path of the directory in which the XLSX file is located, then the following will give you the full path to the file:
file_path = dir(path, pattern = '\\.xlsx$', full.names = TRUE)
Note that pattern uses regular expressions rather than glob format! Using the glob pattern *.xlsx might appear to work but it’s incorrect, only works by accident, and will also match other file names.
Suppose your file is located inside a folder called myFolder located in disk E:\\
library(readxl)
folderPath <- "E://myFolder"
fileName <- grep(".xlsx", dir(folderPath), value = TRUE)
filePath <- paste(folderPath, fileName, sep = "//")
df <- read_xlsx(filePath)
This code will get the name of your xlsx file inside folderPath each time you run it and then you can import it with readxl::read_xlsx. I assume there is only one xlsx file inside the folder.

locating directory where R code is stored

I want to find the directory where my R code file is located. If I attempt to
source("dir/hh.R")
then I would need to know in advance the directory in which the script is located. I would like to automatically identify the directory of my script, so I can call it like this:
pathToMyScript <- findDirectoryOfMyScript("hh.R")
source(paste0(pathToMyScript, "/hh.r"))
What function can I used to find automatically the path of my R code? What would be findDirectoryOfMyScript like?
If you happen to know the name of the script but not the directory it's stored in, you can source it like this:
source(list.files(pattern = "nameOfFile.R", recursive = TRUE))
Notice that you can actually set a real pattern instead of the actual filename, like I used in the example.
Please be aware that if there are more than one file returned by the search done by list.files, source will return an error.

How to supply file names with paths to R's read.table function?

What is the correct method for enter data(d=read.table("WHAT GOES HERE IF YOU HAVE A MACBOOK ") if you have a mac computer?
Also what does the error code list below mean:
d=read.table(“Firststatex.notepad”,header=T)
Error: unexpected input in "d=read.table(‚"
Two usage errors:
You don't use data() to read in to R datasets held in external files. data() is an R function to load datasets that are built in to R and R packages. read.table("foo.txt") will return a data frame object from the file "foo.txt", which you can assign to an object within R using the assignment operator <-, e.g.
DF <- read.table("foo.txt")
As for "what goes here...", you need to supply a file system path from the current directory to the directory holding the file you want to read in. If the file "foo.txt" is in the current working directory, you can just provide the file name with extension as I did above. If the file is in another directory you need to supply the path to the file name and the file name, for example if the file "foo.txt" is located in the directory above the current directory, you would supply "../foo.txt". If it were in a directory myData located in the directory above the current directory you could us "../myData/foo.txt". So paths can be relative to the current directory. You can also use the fully qualified path on your file system hierarchy.
An alternative is to use the file.choose() function in place of the file name string. This will allow you to navigate to the file you wish to load interactively using a native file selection dialogue. This is what happens on Windows and I suspect also on Mac; not much different happens on Linux. For example:
DF <- read.table(file.choose())
You should probably look for specific help for your operating system if you are not familiar with how to specify file names and paths.
I get the same error when copying and pasting in the code you provide. The problem comes from the fact that you are using fancy, curly quotes “Firststatex.notepad” rather than one of the three sets of accepted quote marks: ` , ", and '; each of these is acceptable, i) "Firststatex.notepad", ii) 'Firststatex.notepad', and iii) `Firststatex.notepad` Just because the quotes you used look like quotes to you or I, these aren't quotes as far as most computer programs recognise. MS Word often inserts these quotes when you enter " for example, as do many other applications.

Resources