How to load jpeg picture from directory - r

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()

Related

How do I get R to work with spaces in a file path?

I believe a switch to OneDrive is causing some issues in various packages in R due to spaces being incorporated into the file path name. One shown below is the readxl package. Is there a way to get the package to read the spaces in the file path names? Or is it something other than the spaces that I might have overlooked?
Installation and the loading of the library work fine. However, when trying to import an excel file, it only works if I put the file in a location without spaces in the file path. I need the file to be in OneDrive so that it will be backed up.
install.packages("readxl")
library("readxl")
TRENDS_2020 <- read_excel("C:\\Users\\name03\\OneDrive - Specific Details Here (ABC)\\Backup_12_22_2020\\WQ_ALL_FINAL_WEBSITE_PIVOT_TRENDS_2020.xlsx")
I get the following error when running that:
Error in utils::unzip(zip_path, list = TRUE) :
zip file 'C:\Users\name03\OneDrive - Specific Details Here (ABC)\Backup_12_22_2020\TRENDS_2020.xlsx' cannot be opened
The following does work for the same file that I copy and pasted into my C drive:
TRENDS_2020 <-read_excel("C:\\TRENDS_2020.xlsx")
Zip {utils}
treated as if passed to system, if the filepaths contain spaces they must be quoted e.g. by shQuote.
Statistical Data Analysis ETH Zurich

Read a file in R without changing the working directory

How can others who run my R program read a file(eg: csv) used in my R code without having to change the working directory in setwd()?
I will suggest you use the here() function in the here package in your code like this:
library(here)
Data1 <- read_csv(here("test_data.csv"))
read.csv has a file argument and if I were to quote from the inbuilt R help about file:
If it does not contain an absolute path, the file name is relative to
the current working directory, getwd().
So, providing the absolute path of the file inside the file argument solves this problem.
In Windows
Suppose your file name is test.csv and it's located in D:\files\test_folder (you can get the location of any file from its properties in Windows)
For reading this file you run:
df<-read.csv('D:\\files\\test_folder\\test.csv')
or
df<-read.csv('D:/files/test_folder/test.csv')
Suggested reading: Why \\ instead of \ and Paths in programming languages
Haven't used R in Linux but maybe Getting a file path in Linux might help
Read from web
Just type in the web address of the dataset in the file attribute. Try:
df<-read.csv('https://raw.githubusercontent.com/AdiPersonalWorks/Random/master/student_scores%20-%20student_scores.csv')
Note: This link contains a list of 25 students with their study hours and marks. I myself used this dataset for one of my earlier tasks and its perfectly safe

Calling Skim from inside R

I'm making a simple line in r to automatically open my generated plots.
I output the plots to a file called "plots.pdf" in the same directory as my r file, and at the end i use this two lines to try to open it:
dir <- paste("/Applications/Skim.app/Contents/MacOS/Skim ",getwd(),"/plots.pdf",sep="")
system(dir)
Basically, dir concatenates the full path of the skim app and the full path of the generated plot.
If i run the string stored at dir in a shell it works perfect, it opens the pdf file in Skim, but when i run it with system() from inside R it doesn't work (Skim says 'The document “plots.pdf” could not be opened.').
I believe this is a very little mistake somewhere in the syntax regarding the absolute/relative paths, but haven't managed to find it... Any advice is welcome! (Or a better way to achieve the same)
I found a way to bypass that problem, i just changed the path to Skim for the 'open' command and i let the system to assign the default app for pdf viewing. So:
dir <- paste("open ",getwd(),"/plots.pdf",sep="")
And it works.

Reading an Excel file into an R dataframe from a zipped folder

I have an Excel file (.xls extension) that is inside a zipped folder that I would like to read as a dataframe into R. I loaded the gdata library and set up my working directory to the folder that houses the zipped folder.
When I type in the following syntax:
data_frame1 <- read.xls( unz("./Data/Project1.zip","schools.xls"))
I get the following error messages:
Error in path.expand(xls) : invalid 'path' argument
Error in file.exists(tfn) : invalid 'file' argument
I'm guessing that I'm missing some arguments in the syntax, but I'm not entirely sure what else needs to be included.
Thanks for your help! This R newbie really appreciates it!
Unfortunately, after a quick survey of all the xls functions I know, there is no xls reading function that can recognize the unz output (I would love to be proven wrong here). If it were a 'csv' it would work fine. As it stands, until such a function is written, you must do the loading in two steps extraction and then loading.
To give you a little more control, you can specify which file to unzip as well as the directory to place the files with unzip.
# default exdir is current directory
unzip(zipfile="./Data/Project1.zip", files = "schools.xls", exdir=".")
dataframe_1 <- read.xls("schools.xls")
Sadly, this also means that you must do cleanup afterwards if you don't want the 'xls' file hanging around.

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