Use deriv or D as part of a function - r

I have got the following problem. I am trying to compute a function like:
derivation <- function(function, number) {
derivation <- deriv(~function, "x")
return(derivation(number))
}
For example:
derivation(x^2, 3) {
derivation <- 2*x
return(2*3)
}
I don't care if I have to put the function in the beginning in braces or as an expression. The variable will always be x. Also be open to use D.

One possibility:
f <- function(fun,val) {
expr <- substitute(fun)
d <- deriv(expr,"x",function.arg=TRUE)
g <- attr(d(val),"gradient")
return(g)
}
f(x^2,3)
substitute() converts the argument fun to an expression without evaluating it
deriv(...,function.arg=TRUE) returns a function that computes the value and includes the derivative as an attribute
d(val) calls the function
attr(.,"gradient") extracts the gradient
If you want to return both the function value and its gradient (as a two-element vector), you could use
r <- d(val)
return(c(c(r),attr(r,"gradient"))
in the function (the internal c(r) drops the attributes from r).

Related

Using `curve` with a function from a list

Why does curve not seem to work with elements extracted from a list?
Consider two seemingly identical functions, but built differently:
a <- function(value){
function(x) x + value
}
m <- lapply(1:3, a)
f <- a(1)
all.equal(f, m[[1]])
#[1] TRUE
curve works for f, but not m[[1]]:
> curve(m[[1]])
Error in curve(m[[1]]) :
'expr' must be a function, or a call or an expression containing 'x'
But it works if the object is extracted before:
d <- m[[1]]
curve(d)
Is there a reason for it?
curve() is a "magic" function that tries to interpret its input as an expression when possible; it doesn't always work.
#user2554330 comments that curve() is expecting (from ?curve):
The name of a function, or a call or an expression written as a function of x which will evaluate to an object of the same length as x.
Instead, m[[1]] is an expression that evaluates to a function. In contrast, d is the name of a function. You can get what you want using curve(m[[1]](x)) which makes the input an expression written as a function of x.
In the code below, R looks at the expression passed to curve() and asks whether is.name(sexpr) is TRUE. This test passes for f but fails for m[[1]] (if you want to test it outside of the function context, you need to compare is.name(quote(f)) and is.name(quote(m[[1]])).
Weirdly enough, plot(m[[1]]) does work (it calls plot.function(), which calls curve() with different arguments internally).
sexpr <- substitute(expr)
if (is.name(sexpr)) {
expr <- call(as.character(sexpr), as.name(xname))
}
else {
if (!((is.call(sexpr) || is.expression(sexpr)) && xname %in%
all.vars(sexpr)))
stop(gettextf("'expr' must be a function, or a call or an expression containing '%s'",
xname), domain = NA)
expr <- sexpr
}

r function in function arguments + apply

I'm having troubles using several functions within the same one and calling the arguments generated. I'm using a more complicated function that can be simplified as followed:
func.essai <- function(x) {
g <- sample(seq(1,30), x)
i <- sample(x,1)
func.essai.2 <- function(y,i) {
z <- y+i
}
h <- sapply(g,func.essai.2(y,i))
}
sq <- seq(1,4)
lapply(sq, func.essai)
I'm using arguments that are generated at the beginning of func.essai (and that depend on x) as a fixed input for func.essai.2, here for i, and as a vector to go through on the sapply function, here for g. This code doesn't work as such -- it doesn't recognize y and/or i. How can I rewrite the code to do so?
I think the error you get is because of your use of sapply. This should work instead of your line containing sapply:
h <- sapply(g,func.essai.2, i)
See ?sapply, which tells you that you should provide additional arguments behind the function that you are applying.

R argument is missing, with no default

I want to calculate the log return of data . I define a function and want to load the data. but system always mentions second factor is missing. Otherwise it just calculate the log of row number.
#read data
data <- read.csv(file="E:/Lect-1-TradingTS.csv",header=TRUE)
mode(data)
p<-data["Price"]
#func1
func1 <- function(x1,x2)
{
result <- log(x2)-log(x1)
return(result)
}
#calculate log return
log_return<-vector(mode="numeric", length=(nrow(data)-1))
for(i in 2:nrow(p))
{
log_return[i-1] <- func1(p[(i-1):i])
}
Error in func1(p[(i - 1):i]) : argument "x2" is missing, with no default
Your function func1 was defined to accept two arguments, but you are passing it a single argument: the vector p[(i-1):i], which has two elements but is still considered a single object. To fix this you need to pass two separate arguments, p[i-1] and p[i]. Alternatively, modify the definition of func1 to accept a two-element vector:
func1 <- function(v)
{
x1 <- v[1]
x2 <- v[2]
result <- log(x2)-log(x1)
return(result)
}
Thank you guys,all your answers inspired me. I think I found a solution.
log_return[i-1] <- func1(p[(i-1),"Price"],p[(i),"Price"])
basically you do not need a func for those calcs in R
R's vectorization comes in handy in these cases
data <- read.csv(file="E:/Lect-1-TradingTS.csv",header=TRUE)
mode(data)
p <- data[["Price"]]
logrets <- log(p[2:length(p)]) - log(p[1:length(p)-1])
This vectorized computation will usually also heavily outperform any function you define "by hand".

R code. write a floor function

I want to write a floor function in R, which returns a floating number to its nearest integer. So I tried the below function. It seems that it works if I assign a value to x and run the code inside the function, but it fails when I try to put everything in a function and call the function name later.
Does anyone know how to fix it?
Thanks!
> my_floor <- function(x) {
x <- x-0.5
as.integer(x)
return (x)
}
> y <- 3.1052255
> my_floor(y)
[1] 2.605225
No very sure what you are trying to do but if you simply want the input transformed to the nearest integer towards zero (i.e. floored as you your question goes), the one way to do it would be:
my_floor <- function(x) {
x <- trunc(x)
return (x)
}
This simply discards the non integer part of your input using R's trunc: which you might as well call directly i.e. trunc(y) will still give you the desired result. If you wish to use your function above "as is" then:
my_floor <- function(x) {
x <- x-0.5
x <- as.integer(x) #Store the result of this second step by reassigning x
return (x)
}

Use optimize() for a function which returns several values

Easier to ask by example. If I have a function
fn <- function(x) {
...
return(c(a,b,c))
}
and I wish to maximize (or minimize) with respect to a, but also get the values of b and c at the optimal value.
Of course I can use fn2 <- function(x) fn(x)[1] to determine the optimal value, then call the function again, but I wonder if there is a smarter way of doing this.
optim needs the return value to be a scalar. The documentation says so
fn: A function to be minimized (or maximized), with first
argument the vector of parameters over which minimization is
to take place. It should return a scalar result.
You could write the values of interest to a global variable inside your function though. This isn't necessarily best practice but it could work.
f <- function(x){
.vals <<- c(x, x+1)
x^2
}
optim(1, f)
then after we can look at what is stored in .vals
> .vals
[1] 9.765625e-05 1.000098e+00

Resources