Attempting to access images using R - r

So I am following the guide here which indicates the way to access photos is as follows:
flags <- c(
system.file("img", "flag", "au.png", package = "ggpattern"),
system.file("img", "flag", "dk.png", package = "ggpattern")
)
My goal is to now use this code for my own uses, so I saved a few images in a folder. Here is my directory:
"C:/Users/Thom/Docs/Misc/Testy"
And within the Testy folder, there is a folder called image, holding 3 images. But the following doesn't seem to work and idk why...
images <- c(
system.file("image", "image1.png", package = "ggpattern"),
system.file("image", "image2.png", package = "ggpattern")
)

system.file is for use when a file included in a package. Basically, it will look for the file starting its search path to where your R packages are installed (because this can vary from user to user). system.file will return the resolved path to the file locally
If you already know the absolute path on your local computer (i.e. "C:/Users/Thom/Docs/Misc/Testy") you can use that as just the input to a read function, e.g. readBin("C:/Users/Thom/Docs/Misc/Testy")
If you want to get a little fancy or are like me and can't ever remember which direction of a slash to use on which OS, you can also do something like this which will add in the OS specific path separator:
readBin(file.path("C:", "Users", "Thom", "Docs", "Misc", "Testy"))

Related

Filepath error when specifying output location for write_dta

I would like to programmatically specify the location of my exports when using write.dta. I have my working directory set to a parent folder and my script is in a child folder called "Script". I want the export to be in a child folder called "Data".
setwd("~/Dropbox/Files")
file_output <- "survey"
path_out <- "./Data"
write_dta(df, paste0(file_output,".dta"), path = path_out, version = 12)
However, I keep getting an error message when R is trying to write. It says it's trying to write to the "Script" folder (where my script file is located in) rather than the desired "Data" folder.
Error: Failed to open '/Users/VancityPlanner/Dropbox/Files/Scripts' for writing
If I put the full path, I still get the same error message, whether it's a child folder or the parent folder (working directory) itself, so I don't think write permissions are an issue.
If I try not specifying the filepath, I have no error messages but it saves it to my working directory, which is not where I want it.
write_dta(df, paste0(file_output,".dta"), version = 12)
Below I show where my working directory is pointing and then I change the path of where I want to save the document in the path statement. Note it has the file path G:/ and the dataset name appended all together. I have a PC but no reason why this shouldn't work on a mac.
library(haven)
getwd()
#"C:/Users/myname/Documents"
write_dta(data = mtcars, path = "G:/mtcars.dta", version = 12)

R waldo does not find difference that snapshot test finds in .RData file

looking for a bit of support:
I have done some expect_snapshot_file() tests from the testthat package - and the files end up not matching when being done in different RStudio sessions (I'm guessing that this is related to this).
I opened both files (the original and the .new file) and attempted to compare them using waldo::compare(old,new) - but waldo does not find any differences in the files. Both the snapshot tests and my git system also notes that these files are different, but again I don't know why/where in the file. Note: It is possible to recreate the difference when setting all this up in a git folder - commit the outcomes.RData file, then rename the outcomes.new.RData file to outcomes.RDataand then git will display a difference - but again because it's a binary file, it won't tell me where...
I cannot use the snapshot_review() function because it does not seem to work with .RData files - it immediately gives me a complicated error.
So I would like to investigate where the differences are. I presume that it might be something related to the R session that I'm working in.
I have provided both files here:
https://transfer.sh/7UwTLD/outcomes.new.RData
https://transfer.sh/xgqhL7/outcomes.RData
and then compare them:
download.file("https://transfer.sh/xgqhL7/outcomes.RData", destfile = "outcomes.RData")
download.file("https://transfer.sh/7UwTLD/outcomes.new.RData", destfile = "outcomes.new.RData")
load("outcomes.RData")
old <- outcomes
load("outcomes.new.RData")
new <- outcomes
waldo::compare(old, new)
#> v No differences
Created on 2022-02-13 by the reprex package (v0.3.0)
The original saving function always stays the same:
save_file <- function(outcomes){
path <- tempfile(fileext = ".RData")
save(outcomes, file = path)
path
}
expect_snapshot_file(save_file(outcomes), name = "outcomes.RData")
Is there any other way that snapshot uses "under the hood"? What other aspects could I consider? Are there any other tools how I could compare files under Windows in a useful manner?
Many thanks!

Unable to use here() to get to the correct project directory

I have this weird problem. I was able to get here() to work but it stopped working and I can't figure out how to fix it.
So basically the structure of my file is like:
C:/First/Second/Third/Analysis/Scripts
C:/First/Second/Third/Analysis/Data
I want to easily bounce between data and scripts in the code
If I type here("C:/First/")
and then follow up with here(), R says that I'm at
C:/First/Documents
I'm not able to type here("Second", "Third", "Analysis", "Data", "todayscode.R")
because it puts me in the folder:
C:/First/Documents/Second/Third/Analysis/Data/
Which obviously does not exist.
It's unclear why you say that C:/First/Documents/Second/Third/Analysis/Data/ "does not exist". You will need to create a subdirectory if it doesn't exist, but at the beginning of your problem presentation you implied that was an existing directory.
Sounds like you want something like this possibilities:
setwd("C:/First/Second/Third/Analysis/")
You should first clarify where your version of the here function is coming from by typing here at the console input line and noting which namespace it comes from. If you then wanted to refer to a directory with that starting point you could use this (using the example set up in the here package at the here help page):
library(here); library(readr)
readr::read_csv(
here("data", "penguins.csv"),
col_types = list(.default = readr::col_guess()),
n_max = 3
)

R extension write local data

I am creating a package and would like to store settings data locally, since it is unique for each user of the package and so that the setting does not have to be set each time the package is loaded.
How can I do this in the best way?
You could save your necessary data in an object and save it using saveRDS()
whenever a change it made or when user is leaving or giving command for saving.
It saves the R object as it is under a file name in the specified path.
saveRDS(<obj>, "path/to/filename.rds")
And you can load it next time when package is starting using loadRDS().
The good thing of loadRDS() is that you can assign a new name to the obj. (So you don't have to remember its old obj name. However the old obj name is also loaded with the object and will eventually pollute your namespace.
newly.assigned.name <- loadRDS("path/to/filename.rds")
# or also possible:
loadRDS("path/to/filename.rds") # and use its old name
Where to store
Windows
Maybe here:
You can use %systemdrive%%homepath% environment variable to accomplish
this.
The two command variables when concatenated gives you the desired
user's home directory path as below:
Running echo %systemdrive% on command prompt gives:
C:
Running echo %homepath% on command prompt gives:
\Users\
When used together it becomes:
C:\Users\
Linux/OsX
Either in the package location of the user,
path.to.package <- find.package("name.of.your.pacakge",
lib.loc = NULL, quiet = FALSE,
verbose = getOption("verbose"))
# and then construct with
destination.folder.path <- file.path(path.to.package,
"subfoldername", "filename")`
# the path to the final destination
# You should use `file.path()` to construct such paths, because it detects automatically the correct ('/' or '\') separators for the file paths in Unix-derived systems (Linux/Mac Os X) versus Windows.
Or use the $HOME variable of the user and there in a file - the name of which beginning with "." - this is convention in Unix-systems (Linux/Mac OS X) for such kind of file which save configurations of software programs.
e.g. ".your-packages-name.rds".
If anybody has a better solution, please help!

Why doesn't knitr respect RStudio project details?

In all other cases, when I am working within an RStudio project, I can make references relative to the project root in scripts. So I can, for example, dfX = read.csv("Data/somefile.csv"), where the folder Data is relative to my project root.
The same code in a knitr chunk does not find the file. I guess this is because knitr creates a bunch of temporary directories that it needs to refer to relative to the file location. Is there an easy way to change this behavior? Obviously, I would not like to add the entire path to the project folder -- I am aware that I can easily do this using knitr::opts_knit$set(root.dir = rootPath). That completely breaks maintainability across machines and OSs.
Edit: This seems closely linked to this question.
Presumably you know the path to the package directory when you call 'knit', so how about:
ENV <- new.env()
assign("workingDirectory", getcwd(), envir = ENV)
knitr::knit(...,
# THE ENVIRONMENT IN WHICH THE CODE CHUNKS ARE TO BE EVALUATED
envir=ENV)
Then in your rmd file you can do:
```{r] print(workingDirectory)```
If you're searching for the location of the current install, you can use:
PATH = NULL
for(libPath in .libPaths())
if('myPackage' %in% list.dirs(libPath,FALSE,FALSE)){
PATH = file.path(libPath,'myPackage')
}
if(is.null(PATH))
stop('could not find package directory')
ENV <- new.env()
assign("workingDirectory", PATH, envir = ENV)
knitr::knit(...,
# THE ENVIRONMENT IN WHICH THE CODE CHUNKS ARE TO BE EVALUATED
envir=ENV)
My guess is that the document that you are "knitting" is in a subdirectory itself. It seems that, when you click "Knit PDF", RStudio or knitr will setwd() to the directory containing the file being knitted. So you may need to do something like dfX = read.csv("../Data/somefile.csv") to get the reference right.
I have a working example here.

Resources