Source R into chunk - r

I'm a new in exams so maybe this question is very newbie.
I can't source external R-file (contains re-usable functions) into my .Rnw.
MWE:
functions.r:
x <- 10
question.Rnw
<<echo=FALSE>>=
source('functions.r')
#
\begin{question}
$x=\Sexpr{x}$
\end{question}
generate.r
library('exams')
exams2moodle('question.Rnw')
When I try Rscript generate.r:
Loading required namespace: rmarkdown
Error: chunk 1
Error in file(filename, "r", encoding = encoding) :
cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
cannot open file 'functions.r': No such file or directory
Execution halted
How can I re-use own R-functions in some questions?

All exercises are copied to a temporary directory where they are processed. Thus, you are in a different directory when you make the source() call. So either you need to include it with the full path source("/path/to/functions.r") - or alternatively you can copy the file to the temporary directory. There is a convenience function include_supplement() to do the latter. If functions.r is in the same directory as question.Rnw you simply need to do:
include_supplement("functions.r")
source("functions.r")
in the code chunk at the beginning of question.Rnw.

Related

Error in file(filename, "r", encoding = encoding) : cannot open the connection Some

## this script assumes that it is started in the working directory
tracker_directory<-normalizePath(getwd())
# setting parameters ------------------------------------------------------
# additional R configuration ----------------------------------------------
# load packages
library(magrittr)
setwd(dirname(getwd()))
# load helper functions
source("R/max_departure.r")
# run methodologies -------------------------------------------------------
Here I have the R file which is referencing to other R file
[1]: https://i.stack.imgur.com/s9Mm3.png
Note that dirname(getwd()) returns the parent directory of your current working directory. Maybe that is the issue? If getwd() returns the directory that contains main.R there is no need for the setwd() call, I think.

Spaces in paths in batch mode R

I'm trying to get an R script to run from a batch file so it can be nice and clean for other users. Currently, you drag and drop a CSV file onto the batch file and it passes the file name to the R script for input.
When there's a space in the file path/name it works fine in RStudio but causes problems when I call it from the batch file. When I do that it tries to open the path before the space.
I've tried to reformat the file path from within R by using shortPathName(inputPath) and by replacing spaces with "\ " but it doesn't seem to work.
At the moment, the script is launched with
"%~dp0\R-3.6.0\bin\R.exe" CMD BATCH "--args %~1" "%~dp0\Script.R"
with the script containing
args <- commandArgs(TRUE)
inputPath <- args[1]
inputPath <- shortPathName(inputPath)
inputData <- read.csv(inputPath)
It runs fine from within RStudio but crashes when launched from the batch producing this error message in the output file:
Error in file(file, "rt") : cannot open the connection
Calls: read.csv -> read.table -> file
In addition: Warning message:
In file(file, "rt") :
cannot open file 'file path up to the space': No such file or directory
Execution halted
By no means a R expert, but I'd try
%~dp0\R-3.6.0\bin\R.exe" CMD BATCH "--args %~s1" "%~dp0\Script.R"
The %~s1 should supply the short filename as the argument.
After trying several formulations of the batch file and some debugging, I found that the batch file was passing the first part of the file before the space as the first argument.
After finding that the use of R in CMD BATCH mode is no longer advisable so switched to running using Rscript mode as
"%~dp0\R-3.6.0\bin\Rscript.exe" --vanilla "%~dp0\Script.R" "%~1"
This allowed for the argument to be passed to R with "", and hence with the space.
Since v3.5.1, R accepts file paths with spaces.

Source function in R, error cannot find file - do I have to change working directory?

This may be a duplicate, but I couldn't find a solution when I searched online and it's an issue that has been bugging me for some time. I am given a zip file with 2 .R files, I download the zip and move the .R files into a directory on my computer, let's say "/Users/Home/StatisticsStuff/LearningR/".
My two files are Stats1.R and Stats2.R, and the first line of code in Stats1.R is:
source(Stats2.R)
and I get the following error message:
> source("Stats2.R")
Error in file(filename, "r", encoding = encoding) : cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) : cannot open file 'Stats2.R': No such file or directory
when i run getwd(), to see which working directory I'm in, I get:
getwd()
"/Users/Home"
It seems like it would be a pain to have to change working directories in order to source files? Is there something I'm doing wrong here with regards to what I'm expecting from the source() function? Do I have to put a line in my code above everything else using setwd("whatever the correct wd is").
Any thoughts appreciated!
I added this before sourcing, it worked for me :
setwd(dirname(getwd()))
first write this command list.files() then you can know which location of your R is pointing or see the below image that R-Pointing to then write the source command with correct path. it will be executed.
follow these steps to see the R pointing path.
Go to properties of your R software which is installed as below
Find the Start in path: which is the path R pointing to so in source command use that path

How can I source an R file from the parent directory via the shell?

I'm able to source an R script from the IDE (Rstudio), but not from a command line call. Is there a way to do this without having to supply the full path?
The file I want to source is in the parent directory.
This works:
source('../myfile.R') #in a call from Rstudio
However, this doesn't:
> Rscript filethatsources_myfile.R
Error in file(filename, "r", encoding = encoding) :
cannot open the connection
Calls: source -> file
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
cannot open file '../myfile.R': No such file or directory
Execution halted
This seems like it should be simple, but...
Edit: I'm using GNU bash, version 3.2.53(1)-release (x86_64-apple-darwin13)
In R, relative file locations are always relative to the current working directory. You can explicitly set your working directory like so:
setwd("~/some/location")
Once this is set, you can get your source file relative to the current working directory.
source("some_script.R") # In this directory
source("../another_script.R") # In the parent directory
source("folder/stuff.R") # In a child directory
Not sure what your current working directory is? You can check by submitting getwd().
What if your source file is in, for example, the parent directory but references files relative to its location? Use the chdir= option in source:
source("../another_script.R", chdir = TRUE)
This temporarily changes the working directory to the directory containing the source file for the duration of the source evaluation. Once that's done, your working directory is set back to what it was prior to running source.

testthat in R: sourcing in tested files

I am using the testthat package in R and I am trying to test a function
defined in a file example.R. This file contains a call source("../utilities/utilities.R") where utilities.R is a file with functions written by me. However, when I am trying to test a function from example.R, sourcing it within the testing script gives the following error:
Error in file(filename, "r", encoding = encoding) :
cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
cannot open file '../utilities/utilities.R': No such file or directory
Could you please clarify how to run tests for functions in files that source another file?
Might be a bit late, but I found a solution. Test_that sets the directory holding the test file as the current working directory. See the code below from test-files.r. This causes the working directory to be /tests. Therefore, your main scripts need to source ("../file.R"), which works for testing, but not for running your app.
https://github.com/hadley/testthat/blob/master/R/test-files.r
source_dir <- function(path, pattern = "\\.[rR]$", env = test_env(),
chdir = TRUE) {
files <- normalizePath(sort(dir(path, pattern, full.names = TRUE)))
if (chdir) {
old <- setwd(path)
on.exit(setwd(old))
}
The solution I found was to add setwd("..") in my test files and simply source the file name without the path. source("file.R") instead of source("../file.R"). Seems to work for me.
testthat allows you to define and source helper files (see ?source_test_helpers):
Helper scripts are R scripts accompanying test scripts but prefixed by helper. These scripts are run once before the tests are run.
So what worked perfectly for me is simply putting a file "helper-functions.R" containing the code that I want to source in "/tests/testthat/". You don't have to call source_test_helpers() yourself, testthat will automatically do that when you run tests (e.g., via devtools::test() or testthat::test_dir()).
No great solution to this problem I've found, so far mine has been to set the working directory within each test using the package here.
test_that('working directory is set',{
setwd(here())
# test code here
})
I put the source("C:/Users/.../Utilities.R") in the test file.

Resources