Searching a functions source code - r

In R, you can view the source of a function as a function is simply another object.
I am looking for a way to search through this source code, without knowing the file that the source is saved in.
For example, I might want to know if the function shapiro.test contains the function sort (it does).
If shapiro.test was a string or a vector of strings I would use
grep('sort', shapiro.test)
But as shapiro.test is a function, this gives the error "Error in as.character(x) :
cannot coerce type 'closure' to vector of type 'character'".
I've had no luck trying to coerce the function to a string. Just as an extra, I'm not expecting to be able to search through base functions as they are compiled.

Here a solution using deparse:
> grep ("sort", deparse(shapiro.test))
[1] 5

You could wrap the function in capture.output, which will convert each line to an element in a character vector.
> grep("sort",capture.output(shapiro.test))
[1] 5
Or you could just call edit(shapiro.test) and use the text editor specified by options(editor=) to search through the function.

Related

Referring to package and function as arguments in another function

I am trying to find methods for specific functions across different packages in R. For example methods(broom::tidy) will return all methods for the function tidy in the package broom. For my current issue it would be better if I could have the methods function in another function like so:
f1 <- function(x,y){
methods(x::y)
}
(I removed other parts of the code that are not relevant to my issue.)
However when I run the function like this:
f1 <- function(x,y){ methods(x::y)}
f1(broom,tidy)
I get the error
Error in loadNamespace(name) : there is no package called ‘x’
If I try to modify it as to only change the function but keep the package the same I get a similar error :
f2 <- function(y){ methods(broom::y)}
f2(tidy)
Error: 'y' is not an exported object from 'namespace:broom'
How can I get the package and function name to evaluate properly in the function? Does this current issue have to do with when r is trying to evaluate/substitute values in the function?
Both the :: and methods() functions use non-standard evaluation in order to work. This means you need to be a bit more clever with passing values to the functions in order to get it to work. Here's one method
f1 <- function(x,y){
do.call("methods", list(substitute(x::y)))
}
f1(broom,tidy)
Here we use substitute() to expand and x and y values we pass in into the namespace lookup. That solves the :: part which you can see with
f2 <- function(x,y){
substitute(x::y)
}
f2(broom,tidy)
# broom::tidy
We need the substitute because there could very well be a package x with function y. For this reason, variables are not expanded when using ::. Note that :: is just a wrapper to getExportedValue() should you otherwise need to extract values from namespaces using character values.
But there is one other catch: methods() doesn't evaluate it's parameters, it uses the raw expression to find the methods. This means we don't actually need the value of broom::tidy, we to pass that literal expression. Since we need to evaluate the substitute to get the expression we need, we need to build the call with do.call() in order to evaluate the substitute and pass that expression on to methods()

R: syntax of svychisq and summary on a svytable

I'm working on a "svydesigned" database and having trouble using svysq.
Here's what I tried which worked:
AxB<-svytable(~A+B, surveydesign, Ntotal=100)
AxB
svychisq(~A+B, surveydesign)
And what I would like to make work:
svychisq(AxB, surveydesign)
returns "$ operator is invalid for atomic vectors"
svychisq(~AxB, surveydesign)
returns "Error in formula [[2]][[2]] : Object of type symbol is not subsettable"
summary(AxB)
returns the table and the chisq, but with integers in the table (so only 0 and 1 since my values are in 0.xx format due to Ntotal=100)
What bugs me is that the help states that "sumary on svytable calls svychisq". I'm still new to R syntax and can't figure out how to make svychisq return a result using the table instead of typing again the whole formula I just used to create the table.
I'd also like to be able to see the decimals when usign "summary", is there a way? I tried to use digits=4 but nothing changed.
Thanks.
svychisq expects a formula and a svydesign object as arguments. It is just the way it was created, you won't be able to feed it a svytable argument. You could work around by writing your own function:
FOO <- function(x){
temp <- as.character(attr(x, "call"))[2:3]
svychisq(as.formula(temp[1]), design = eval(parse(text = temp[2])))
}
You feed it a svytable object, it retrieves the call of the object and feeds it back to svychisq.
FOO(AxB) should work as expected.

Extract argument code of a function in R/Subset function based on argument names

I am working with caret package. There are many functions which uses methods inside it. Example,
rfe
methods(rfe)
rfe.default
To check arguments of rfe.default we use args() function, or formalArgs() or formals()
args(rfe.default)
formalArgs(rfe.default)
formals(rfe.default)
Now, I just want to see the codes for each argument used inside rfe.default function, instead of whole function code which we get by typing
rfe.default
How to get the codes just for those arguments.
We can use deparse() function to get the range of lines from the function code. But is there any way to get the codes of arguments from the function based on argument names.
If an argument is using a function within it like here rfeContol = rfeControl()
I should be able to extract just this argument's code from rfe.default function instead of the whole code or rfe.default.
Thanks.

Error: unexpected string constant in file path in R

I am trying to run this command in R in order to run a function:
xlsxToR <- function("C:\\Users\\Nabila\\Dropbox\\IsolutionsProject\\ServiceRequestTickets.zip", keep_sheets = "TicketDetails", header = FALSE)
However, I tend to get this error when I run it:
Error: unexpected string constant in "xlsxToR <- function("C:\\Users\\Nabila\\Dropbox\\IsolutionsProject\\ServiceRequestTickets.zip""
I have tried looking for a mistake in my file path. Tried using forward slashes but to no avail. Can anyone help please?
Functions in R
When you are using function in R you are defining a function (You can use ?function to see the documentation). Inside the parentheses after function you set the arguments of the function. You can also set default values for those arguments using =. After that the body of the function should follow, i.e. an R expression containing the code of the function.
Your case
This line of code does not run a function. It defines a function with name xlsxToR. The first thing in the parenthesis is a string, not an argument name, which causes the error. Also your function is just a definition of some argumnents without a body, which probably is not what you are trying to do.

Passing package name as argument in R

I see myself keep using the install.package function a lot especially when I have to try out someone else's code or run an example.
I as writing a function that installs and loads a package. I tried the following but it did not work:
inp <- function(PKG)
{
install.packages(deparse(substitute(PKG)))
library(deparse(substitute(PKG)))
}
When I typed inp(data.table), it says
Error in library(deparse(substitute(PKG))) :
'package' must be of length 1
How do I pass library name as argument in this case?
I will appreciate if someone can also direct me to information pertaining to passing any kind of object as argument to a function in R.
library() is throwing an error because it by default accepts either a character or a name as its first argument. It sees deparse(substitute(PKG)) in that first argument, and understandably can't find a package of that name when it looks for it.
Setting character.only=TRUE, which tells library() to expect a character string as its first argument, should fix the problem. Try this:
f <- function(PKG) {
library(deparse(substitute(PKG)), character.only=TRUE)
}
## Try it out
exists("ddply")
# [1] FALSE
f(plyr)
exists("ddply")
# [1] TRUE

Resources