Fortranner
Fortranner

Reputation: 2605

How to determine which R package contains a function?

In Python one can write

import numpy as np
print np.random.randn(10)

to make clear that the function random.randn comes from numpy.

When I download an R code from the web, such as the one below, I'd like to know which functions are imported from each library. Is there a way to do this other than commenting out each "library" statement and seeing where the code breaks?

library(pracma)
library(quantmod)
library(fractaldim)

calculate_EI <- function(fxdata){

colnames(fxdata) <- c("data")

approx_entropy_for_symbol <- approx_entropy(fxdata, edim = 2, r = 0.2*sd(fxdata), elag = 1)
random_dist <- rnorm(length(fxdata))
approx_entropy_threshold <- approx_entropy(random_dist, edim = 2, r= 0.2*sd(random_dist), elag = 1) 

fractal_dimension_for_symbol <- fd.estimate(as.data.frame(fxdata$data)$data)$fd
hurst_exponent_for_symbol <- hurstexp(as.data.frame(fxdata$data)$data, d = 50)$Hal

EI$value <- ((approx_entropy_for_symbol-approx_entropy_threshold)/approx_entropy_threshold)^2
EI$approx_entropy_contribution <- ((approx_entropy_for_symbol-approx_entropy_threshold)/approx_entropy_threshold)^2
EI$value <- EI$value + ((fractal_dimension_for_symbol-1.5))^2
EI$fractal_dimension_contribution <- ((fractal_dimension_for_symbol-1.5))^2
EI$value <- EI$value + ((hurst_exponent_for_symbol-0.5))^2
EI$hurst_exponent_contribution <- ((hurst_exponent_for_symbol-0.5))^2
EI$value <- sqrt(EI$value)

return(EI)
}

#sample case
getSymbols("EUR/USD",src="oanda") 
fxdata <- EURUSD
EI <- calculate_EI(fxdata)
EI

Upvotes: 3

Views: 1713

Answers (1)

Rorschach
Rorschach

Reputation: 32466

There are some useful functions for finding objects like getAnywhere and the package sos if you don't have the packages on your search path. Also, one could use the parsing data to try and do it programmatically, but it won't get everything, like in cases where functions are passed as strings or other weird cases. Anyway, here is a quick example if you had that code stored in "test.R" (as @javK noted, the packages would need to be loaded so getAnywhere can find them in this example).

src <- parse(file="test.R", keep.source = TRUE)
tokens <- getParseData(src)
funs <- tokens[tokens$token == "SYMBOL_FUNCTION_CALL",]
res <- lapply(funs$text, function(x) getAnywhere(x)$where)

## Return a list of the functions along with the environment they in
## truncated...
setNames(res, funs$text)
# ...
# $c
# [1] "package:base"   "namespace:base"
# $approx_entropy
# [1] "package:pracma"   "namespace:pracma"
# $sd
# [1] "package:stats"   "namespace:stats"
# $rnorm
# [1] "package:stats"   "namespace:stats"
# ...

Upvotes: 5

Related Questions