Where is the .R script file located on the PC? - r

I want to find the location of the script .R files which are used for computation in R.
I know that by typing the object function, I will get the code which is running and then I can copy and edit and save it as a new script file and use that.
The reason for asking to find the foo.R file is
Curiosity
Know what is the algorithm used in the numerical computations
More immedietly, the function from stats package I am using, is running results for two of the arguments and not the others and have to figure out how to make it work.
Error shown by R implies that there might be some modification required in the script file.
I am looking for a more general answer, if its possible.
Edit: As per the comments so far, here is the code to compute spectrum of a time series using autoregressive methods. The data input is a univariate series.
x = ts(data)
spec.ar(x, method = "yule-walker") 1
spec.ar(x, method = "burg") 2
command 1 is running ok.
command 2 gives the following error.
Error in ar.burg.default(x, aic = aic, order.max = order.max, na.action = na.action, :
Burg's algorithm only implemented for univariate series
I did try specify all the arguments correctly like na.action=na.fail, order.max = NULL etc but the message is the same.
Kindly suggest possible solutions.
P.S. (This question is posted after searching the library folder where R is installed and zip files which come with packages, manuals, and opening .rdb, .rdx files)

See FAQ 7.40 How do I access the source code for a function?
In most cases, typing the name of the function will print its source
code. However, code is sometimes hidden in a namespace, or compiled.
For a complete overview on how to access source code, see Uwe Ligges
(2006), “Help Desk: Accessing the sources”, R News, 6/4, 43–45
(http://cran.r-project.org/doc/Rnews/Rnews_2006-4.pdf).

When R installs a package, it evaluates all the ".R" source files and re-saves them into a binary format for faster loading. Therefore you typically cannot easily find the source file.
As has been suggested elsewhere, you can simply type the function name and see the source code, or download the source package and find the source there.
library(plyr)
ddply # prints the source for ddply
# See the content of the R directory for plyr,
# but it's only binary files:
dir(file.path(find.package("plyr"), "R"))
# [1] "plyr" "plyr.rdb" "plyr.rdx"
# Get the source for the package:
download.packages("plyr", "~", type="source")
# ...then unpack and inspect the R directory...

.libPaths() should tell you all of your current library locations. It's possible to have more than one installation of a package if there are two libraries but only the one that is in the first library will be used. Unless you offer the code and the exact error message, it's not likely that anyone will be able to offer better advice.

I think you are asking to see what I call the source code for a function in a package. If so, the way I do it is as follows, which has worked successfully for me on the three times I have tried. I keep these instructions handy in a few places and just copied and pasted them here:
To see the source code for a function in Program R download the package containing the function. Specifically, download the file that ends in "tar.gz". This is a compressed file. Expand the compressed file using, for example, "WinZip". Now you need to open the uncompressed file that ends in ".tar". Download the free software "7-Zip". Click on the file "7zFM.exe" and navigate to the directory containing the ".tar" file. You can extract the contents of that ".tar" file into a new folder. The contents consist of R files showing the source code for the functions in the R package.
EDIT:
Today (July 8, 2012) I was able to open the 'tar.gz' file using the latest version of 'WinZIP' and could copy the contents (the source code) from there without having to use '7-Zip'.
EDIT:
Today (January 19, 2013) I viewed the source code for functions in base R by downloading the file
'R-2.15.2.tar.gz'
To download that file go to the http://cran.at.r-project.org/ webpage and click on that file in this line:
"The latest release (2012-10-26, Trick or Treat): R-2.15.2.tar.gz, read what's new in the latest version."
Unzip the file. WinZip will work, or it did for me. Then search your computer for readtable.r or another base R function.
agstudy noted here https://stackoverflow.com/questions/14417214/source-file-for-r-function that source code for read.csv is located in the file readtable.r, so do not expect every base R function to have its own file.

Related

Missing command in an R package

So to get to the point: I need to use an R package called machuruku. To get familiar with the package I used the dataset provided in the original paper (https://academic.oup.com/sysbio/article/70/5/1033/6171196). While trying to run the code for the simulation I get an error message saying that the command "machu.simulation" doesn't exist. Any of you have any idea why that's happening? Am I missing a package?
I downloaded the dataset zip file, dove into the second nested zip file Guillory_and_Brown_simulation-validation.zip, then into its file code_simulation-validation.R, and noticed that this source file uses machu.simulation several times before defining the function starting in line 519.
Suggestions:
Grab lines 519 through the end, save into a different file, source that new file, then try to run the code in the beginning of the file again.
Complain (not quietly?) to the authors, the fact that they think this is reproducible means they might have missed something else, too.

How to include raw data in an R package

I'm working on the final assignment of the course Building R Packages.
In this assignment, we need to create an R package based on some example functions provided by the instructors. We need to organize and document the package, then make it available on GitHub. My package is called FARS and is already available in this GitHub repo.
I'm having trouble with making raw data available with the package. After following the instructions provided in the course's readings and also in chapter 14.3 of the book Building R Packages, the files are still not being recognized.
What did I do so far?
Prepared all the package's documentation, including roxygen2 tags, DESCRIPTION, README.Md, and vignette, following these steps in addition to instructions provided in the readings and book mentioned;
Created a subdirectory named inst/extdata in the package's directory;
Copied all three example files (.csv.bz2) with raw data to inst/extdata;
Tested the functions using testthat;
Installed my FARS package.
Now I'm trying to check if one of the files is available after installing the package:
system.file("extdata", "accident_2013.csv.bz2",
package = "FARS",
mustWork = TRUE)
I get an error message:
Error in system.file("extdata", "accident_2013.csv.bz2", package = "FARS", :
no file found
These data files need to be available with the package, so the examples provided in the vignette work properly.
Here's a "real-life" example, using a simple package I wrote recently.
I have a "data" directory in the build directory.
EDIT To clarify the comments found in R-exts, the directory tree packagename/inst/extdata is intended for data that your functions call directly, by specifying that directory path. Since you want to load data into your workspace, use the data directory.
My "data" directory contains one file named preciseNumbersAsChar.r . That file contains assignments such as
charE <- {long number string}
If you read the help page for the command data, it explains that files ending in .r are sourced when called.
library(FunWithNumbers)
data('preciseNumbersAsChar') #works
Which is to say, the defined objects are now in my environment.
It's worth reading the help page for data in detail as different file types are handled slightly differently.

How to access/open arbitrary formatted (.pdf etc) documents from R's console?

http://cran.r-project.org/doc/manuals/r-release/R-exts.html#Writing-package-vignettes states:
"...In addition to the help files in Rd format, R packages allow the inclusion of documents in arbitrary other formats. The standard location for these is subdirectory inst/doc of a source package, the contents will be copied to subdirectory doc when the package is installed. Pointers from package help indices to the installed documents are automatically created. Documents in inst/doc can be in arbitrary format, however we strongly recommend providing them in PDF format, so users on almost all platforms can easily read them..."
I used roxygen package. It produced .Rd files for me. I produced .pdf of my package via " R CMD Rd2pdf causfinder/" from Windows command line ( or, via during build/install process via "roxygenize("causfinder"); build("causfinder"); install("causfinder")".)
I wanted to add some supplementary .pdf help files (that I created outside of R; from Word via save as .pdf etc.) to my package other than the one that is produced via above techniques. These supplementary .pdf files include the detailed mathematical theory and lots of samples of the functions of my package which illustrate the usage of the functions via various plots, graphs, etc. I called it TheoryOfcausfinder.pdf.
I wanted to add this supplementary .pdf file to my package. As is directed from R's above manual, I put TheoryOfcausfinder.pdf to inst\doc folder in my R's working directory. Upon build/install process, I obtained causfinder/doc/index.html and causfinder/doc/TheoryOfcausfinder.pdf in my R's library location.
The content of index.html:
"...Vignettes from package 'causfinder': The package contains no vignette meta-information.
Other files in the doc directory: TheoryOfcausfinder.pdf..."
I want the future users of causfinder to easily access/open this supplementary TheoryOfcausfinder.pdf. (I will add that there is such a file in functions' help documents)
Is there a way to open/access TheoryOfcausfinder.pdf in R's library location from (within) R's console?
(Important: By the way, since I am novice of Sweave and knitr, I do not wanna enter that path! I look for a solution outside Sweave and knitr.)
Any help will be greatly appreciated.
I don't know if you have found another solution or not yet, but I am posting some possible ideas below.
source http://www.r-bloggers.com/show-me-the-pdf-already/
# under Unix types
pdf <- getOption("pdfviewer", default='')
f <- system.file("doc", "TheoryOfcausfinder.pdf", package = "causfinder")
system2(pdf, args = f)
source http://www.r-bloggers.com/show-me-the-pdf-already/
# under MS Windows
f <- system.file("doc", "TheoryOfcausfinder.pdf", package = "causfinder")
shell.exec(normalizePath(f))
source Opening PDF within R studio using file.show studio-using-file-show/33791818
# under OS X
f <- system.file("doc", "TheoryOfcausfinder.pdf", package = "causfinder")
system2('open', args = f, wait = FALSE)

How to take data files info to index and how to update a data file in an existing R package properly?

I have written an R package in which the names of the functions are in Turkish.
I wanna take that package to CRAN with internalization. I changed all of the Turkish names (of functions, of data sets) to English so that everybody can easily use the package. After that, I followed regular "library(roxygen2); library(devtools); library(digest); roxygenize("causfinder"); build("causfinder"); install("causfinder"); library(causfinder)" way in process.
At the end, all of the functions appear with their English names this time in the Object Browser of Revolution R (version 7.1.0 Academic License). So, for the conversion of the names of the functions, all are OK.
Problem:
But, interestingly, not all of the names of data files in the package are not converted to English.
What I did to solve the problem till now:
I tried every sort of trick I know:
1. I deleted package from library location (I have only 1 such location: "C:\Revolution\R-Enterprise-7.1\R-3.0.2\library") completely and rebuild package and install again.
2. I deleted package from working directory "C:\Users\erdogan\Documents\Revolution", and triggered "library(roxygen2); library(devtools); library(digest); roxygenize("causfinder"); build("causfinder"); install("causfinder"); library(causfinder)" process
3. By giving possibility to Buffer effects, I deleted "C:\Users\erdogan\Documents\Revolution\32_7.1" so that "PackageXMLs\causfinder.xml" in that folder does not meddle in improperly. I had R created "32_7.1" folder by restarting Revo R.
4. I applied tricks suggested by "Dirk Eddelbuettel" here:
Update the dataset in an installed package
"updating the source and re-installing with a new distinctive version number": Not worked.
"by forcefully overwriting it, possibly. Not the proper way to do it.": How to apply that force?
My findings that may perhaps give an idea to professionals to solve the problem:
Only one of the data files correctly got renamed, and at the end of that data file in object browser "[Package causfinder version 1.0 Index]" appears. The names of all the other data files are still in Turkish and at the end of those data files, the phrase "[Package causfinder version 1.0 Index]" does not appear! I did not do anything peculiar to that data file whose internalization was done correctly.
Any help will be greatly appreciated.
Step by Step Solution: (Notebook with 32-bit Windows; GUI: Revolution R Enterprise (32-bit))
1. Prepare the environment by cleaning related folders:
1a. Delete the package folder in R's library location via Windows Explorer:
(I have only 1 such location: I deleted "C:\Revolution\R-Enterprise-7.1\R-3.0.2\library\causfinder" folder)
(Run ".libPaths()" to see R's library locations and delete the package's folder from all R's library locations)
1b. Delete the package folder in R's working directory via Windows Explorer:
(I have only 1 such location: I deleted "C:\Users\erdogan\Documents\Revolution\causfinder" folder)
(Run "getwd()" to see R's working directory and delete the package's folder from all R's working directories)
1c. Delete the "32_7.1" or "64_7.1" folder (32bit, 64 bit R, whichever you use) from R's working directory via Windows Explorer:
The .xml file of the package in discussion in this folder may sometimes meddle in and affect the results of R commands, and gives unexpected results.
Delete "C:\Users\erdogan\Documents\Revolution\32_7.1" folder where "PackageXMLs\causfinder.xml" is located.
(When Revolution R restarted, 32_7.1 (or 64_7.1) folder is created automatically if it doesn't exist)
Restart Revolution R now.
2. Create .rda and .Rd files via R and put them in relevant location.
((For English ones, I created .rda and .Rd files like this:
V6Stationary43Obs.df <-
read.csv("C:/Users/erdogan/Documents/Revolution/V6Stationary43ObsWithoutX.csv", header = TRUE, stringsAsFactors = FALSE)
# create V6Stationary43Obs.df.rda dataset file; df to denote data frame
save(V6Stationary43Obs.df, file="V6Stationary43Obs.df.rda")
prompt(V6Stationary43Obs.df) # creates V6Stationary43Obs.df.Rd help file))
((For Turkish ones, I performed the followings once upon a time
D6Duragan43Gozlem.dvc<- read.csv("C:/Users/erdogan/Documents/Revolution/D6Duragan43GozlemXsiz.csv", header = TRUE, stringsAsFactors = FALSE)
# create D6Duragan43Gozlem.vc.rda dataset file; df to denote data frame
save(D6Duragan43Gozlem.vc, file="D6Duragan43Gozlem.vc.rda")
prompt(D6Duragan43Gozlem.vc) # create D6Duragan43Gozlem.vc.Rd help file))
3. Take the .rda and .Rd files (created in Step2) to the "data" and "man" folder in R's working directory via Windows Explorer:
V6Stationary43Obs.df.rda dataset file --> C:\Users\erdogan\Documents\Revolution\causfinder\data
V6Stationary43Obs.df.Rd help file --> C:\Users\erdogan\Documents\Revolution\causfinder\man
4. Fill at least the "Title" and "Description" tags of .Rd files (created in Step3) via R:
"File - Open - File... - V6Stationary43Obs.df.Rd"
\title{
V6Stationary43Obs is..... .
}
\description{
V6Stationary43Obs does..... .
}
5. Apply roxygenization:
library(roxygen2)
library(devtools)
library(digest)
roxygenize("causfinder")
build("causfinder")
install("causfinder")
library(causfinder)
Solution: (Notebook with 64-bit Windows; GUI: Revolution R Enterprise (32-bit))
The above process is performed with the following additional actions:
1. The datasets are created as usual (for example; ".df" to denote data frame):
X.df <- read.csv("C:/Users/erdogan/Documents/Revolution/X.csv", header = TRUE, stringsAsFactors = FALSE)
save(X.df, file="X.df.rda") # X.df.rda dataset is created
prompt(X.df) #X.df.Rd help file is created.
2. Revolution R is closed, and in the working directory, the folder "32_7.3" is deleted. We delete this folder because: The information (functions, data sets, etc.) of our package (here: causfinder) are stored as .xml file in 32_7.3. However, this .xml file cannot update itself once we add our data sets one by one.
3. Revolution R is opened (the folder "32_7.3" is re-created). At this point, Step 5 above (Applying roxygenization) is performed. Once we do this, the datasets are visible in Revolution R's Object Browser.
4. The control of everything realized seamlessly: Go to the "data" folder of package's library location. Here, you must see only ".rdb, .rds, .rdx" files.
Solution: (Notebook with 64-bit Windows; GUI: Revolution R Enterprise (64-bit))
Apply the steps for 32-bits. If everything is OK, then fine: you are done. If not OK (i.e. datasets are not visible in Object Browser of Revo R and data folder of the package in the library location does not include only the .rdb, .rds, .rdx files), then do not panic:
You can still work with the datasets you created that are seen as .rda files in the package's library location: Use "data" command:
data(YourDatasetName, package = causfinder, lib.loc = YourLibraryLocation)
Learn about data command more. Upon using this command, you get the dataset in the Object Browser as an object of Global Environment.

The cause of "bad magic number" error when loading a workspace and how to avoid it?

I tried to load my R workspace and received this error:
Error: bad restore file magic number (file may be corrupted) -- no data loaded
In addition: Warning message:
file ‘WORKSPACE_Wedding_Weekend_September’ has magic number '#gets'
Use of save versions prior to 2 is deprecated
I'm not particularly interested in the technical details, but mostly in how I caused it and how I can prevent it in the future. Here's some notes on the situation:
I'm running R 2.15.1 on a MacBook Pro running Windows XP on a bootcamp partition.
There is something obviously wrong this workspace file, since it weighs in at only ~80kb while all my others are usually >10,000
Over the weekend I was running an external modeling program in R and storing its output to different objects. I ran several iterations of the model over the course of several days, eg output_Saturday <- call_model()
There is nothing special to the model output, its just a list with slots for betas, VC-matrices, model specification, etc.
I got that error when I accidentally used load() instead of source() or readRDS().
Also worth noting the following from a document by the R Core Team summarizing changes in versions of R after v3.5.0 (here):
R has new serialization format (version 3) which supports custom serialization of
ALTREP framework objects... Serialized data in format 3 cannot be read by versions of R prior to version 3.5.0.
I encountered this issue when I saved a workspace in v3.6.0, and then shared the file with a colleague that was using v3.4.2. I was able to resolve the issue by adding "version=2" to my save function.
Assuming your file is named "myfile.ext"
If the file you're trying to load is not an R-script, for which you would use
source("myfile.ext")
you might try the readRDSfunction and assign it to a variable-name:
my.data <- readRDS("myfile.ext")
The magic number comes from UNIX-type systems where the first few bytes of a file held a marker indicating the file type.
This error indicates you are trying to load a non-valid file type into R. For some reason, R no longer recognizes this file as an R workspace file.
Install the readr package, then use library(readr).
It also occurs when you try to load() an rds object instead of using
object <- readRDS("object.rds")
I got the error when saved with saveRDS() rather than save(). E.g. save(iris, file="data/iris.RData")
This fixed the issue for me. I found this info here
Also note that with save() / load() the object is loaded in with the same name it is initially saved with (i.e you can't rename it until it's already loaded into the R environment under the name it had when you initially saved it).
I had this problem when I saved the Rdata file in an older version of R and then I tried to open in a new one. I solved by updating my R version to the newest.
If you are working with devtools try to save the files with:
devtools::use_data(x, internal = TRUE)
Then, delete all files saved previously.
From doc:
internal If FALSE, saves each object in individual .rda files in the data directory. These are available whenever the package is loaded. If
TRUE, stores all objects in a single R/sysdata.rda file. These objects
are only available within the package.
This error occured when I updated my R and R Studio versions and loaded files I created under my prior version. So I reinstalled my prior R version and everything worked as it should.

Resources