I have 1 know value of x. and I too have 1 formula. y = 0.92x now I want to flip LHS to RHS expected output will be x = y/0.92 its for multiplication and division. It should handle all basic mathematical operations. Is there any package for this in R or any one have defined function in R
I don't think there is any way to accomplish what you want. Rewriting mathematical formulas while they are represented as R functions is not an easy thing to do. What you can do is use uniroot to solve functions. For example:
# function for reversing a function. y is your y value
# only possible x values in interval will be considered.
inverseFun = function(y, fun, interval = c(-1e2, 1e2), ...) {
f = function(.y, .fun, ...) y - fun(...)
uniroot(f, interval, .y = y, .fun = fun, ...)
}
# standard math functions
add = function(a, b) a + b
substract = function(a, b) a - b
multiply = function(a, b) a * b
divide = function(a, b) a / b
# test it works
inverseFun(y = 3, add, b = 1)
# 2
inverseFun(y = -10, substract, b = 1)
# -9
inverseFun(y = 30, multiply, b = 2)
# 15
inverseFun(y = 30, divide, b = 1.75)
# 52.5
The above is an example, inverseFun(y = 3, `+`, b = 1) also works although it might be less clear what is happening. A last remark is that uniroot tries to minimize a function which might be time consuming for complicated functions.
Related
Once in a blue moon I need to use the lovely uniroot.all function from the rootSolve package to find the root(s) of a function with multiple arguments. Every time I do this I run into a bunch of snags which I eventually resolve, but then forget how I resolved them the next time around. So, this time I am registering the snags here so that hopefully next time I can just look here and see how to resolve them quickly.
Here is some example code:
testFn <- function(x, a, b, thresh){
f <- a * x^2 - b
slack <- f - thresh
return(slack)
}
a <- 1
b <- 2
thresh <- 0
xGuess <- 1
testFn(xGuess, a, b, thresh)
interval <- c(0, 2)
testRoot <- rootSolve::uniroot.all(testFn,
interval = interval,
lower = min(interval),
upper = max(interval),
x = xGuess,
a = a,
b = b,
thresh = thresh)
This should give a root of x equals square root of 2, but instead throws the following error:
Error in f(xseq, ...) : unused argument (xseq)
I think the problem has something to do with how I pass extra parameters like a, b, thresh to testFn()
Your problem is including x = xGuess:
library(rootSolve)
uniroot.all(testFn,
interval = interval,
lower = min(interval),
upper = max(interval),
#x = xGuess,
a = a,
b = b,
thresh = thresh)
## [1] 1.41418
If you type uniroot.all (without the () ) you can see the code. It calls f(xreg, ...), which works if the first argument is x and only the extra arguments (a, b, and thresh in your case) are specified.
I want to find the maximum of a scalar function
delta <- function(a,b) {
t(f(b)) %*% Ninv %*% f(a)
}
where a and b are vectors with length=2, over a meshgrid.
The idea is basically to exchange a 2-d point (a) in design0 with a 2-d point (b) in candidate, to gain maximum increment in delta. I want to try all combinations from
design0 = matrix(c(-1, 1, -1, 1, -1, -1), 3)
# 3 by 2 matrix
candidate=expand.grid(seq(-1,1,0.01), seq(-1, 1, 0.01))
# 40401 by 2 matrix
and it should return a 3 by 40401 matrix.
I first think of something like
outer(design0, t(candidate), delta)
but it seems like outer does not work with 2 dimension.
Then I think of use mapply
mapply(delta,a=...,b=...)
I need something like expand.grid(design0, candidate) to make a and b match. That does not work either.
If they all fail, in the end I may use nested loop... but I hate loops when dealing with matrices. This is already a part inside a iteration.
Below is executable code
beta0=9; beta1=5; beta2=5;
design0 = matrix(c(-1,1,-1,1,-1,-1),3)
candidate = expand.grid( seq(-1,1,0.01), seq(-1,1,0.01))
f <- function(x){
eta = beta0 + beta1*x[1] + beta2*x[2]
sqrt(exp(-eta)/(1+exp(-eta))^2)*c(1,x[1],x[2])
}
Fmat = t(apply(design0,1,f))
Ninv = solve(t(Fmat) %*% Fmat)
delta <- function(a,b) {
t(f(b)) %*% Ninv %*% f(a)
}
My question concerns something that should be fairly simple, but I can't make it work. What I mean is you can calculate x and y and then plot them with the plot function. But can this be done using the curve function?
I want to plot the following R function f2:
n <- 1
m <- 2
f2 <- function(x) min(x^n, x^(-m))
But this code fails:
curve(f2, 0, 10)
Any suggestions?
You need to use vectorised pmin instead of min (take a look at ?pmin to understand the difference)
f2 = function(x, n = 1, m = 2) {
pmin(x^n, x^(-m))
}
curve(f2, from = 0, to = 10)
On a side note, I would make n and m arguments of f2 to avoid global variables.
Update
To plot f2 for different arguments n and m you would do
curve(f2(x, n = 2, m = 3), from = 0, to = 10)
As has been hinted at, the main reason why the call to curve fails is because curve requires a vectorized function (in this case feed in a vector of results and get out a vector of results), while your f2() function only inputs and outputs a scalar. You can vectorize your f2 on the fly with Vectorize
n <- 1
m <- 2
f2 <- function(x) min(x^n, x^(-m))
curve(Vectorize(f2)(x), 0, 10)
Is the curve function needed or would this work?
n <- 1 # assumption
m <- 2 # assumption
f2 <- function(x) min(x^n, x^(-m))
x.range <- seq(0, 10, by=.1)
y.results <- sapply(x.range, f2) # Apply a Function over a List or Vector
# plot(x.range, y.results) old answer
plot(x.range, y.results, type="l") # improvement per #alistaire
I want to get the derivative value from the function below when x = 2. Is there way to keep the form of the function and also get derivative value with out any additional package?
f <- function(x)
return(x^3)
For example, I have tried below but they didn't work.
x=2
deriv(~f, "x")
x=2
deriv(~body(f),"x")
x=2
D(expression(f),"x")
You can use deriv, however, one caveat is that you can only use expressions/calls.
derivative = deriv(~ x^3, "x")
x <- 2
eval(derivative )
With a named expression:
f = expression(x^3)
dx2x <- D(f,"x")
and the rest is the same.
See this link for the documentation:
https://www.rdocumentation.org/packages/Deriv/versions/3.8.2/topics/Deriv
This would be approximation
foo = function(x, delta = 1e-5, n = 3){
x = seq(from = x - delta, to = x + delta, length.out = max(2, n))
y = x^3
mean(diff(y)/diff(x))
}
foo(2)
#[1] 12
I have a data set dat and two lists x and y. I would like to calculate different combination of x and y with different value of k. I wrote the following code to find the value of function fun for these different combinations. but how can I get the value of k which maximize the function fun for these different combination? since in each iteration I have different lists of x and y and at the end I want to find the k which maximise the function fun.
dat = c(9, 2, 7)
k = seq(0, 1, length = 10)
x =list(a = 1, b = 8, c = 4)
y = list(a = .5, b = 5, c = 5)
matrix = cbind(unlist(x), unlist(y)) %*% rbind(1-k, k)
z = apply(matrix, 2, as.list)
fun = function(dat, vec) sum(vec$a * dat - vec$b * dat + vec$c * dat)
res = rep(0, length(k))
for (i in 1:(length(k))){
v = split(unlist(z[[i]]), sub("\\d+$", "", names(z[[i]])))
res[i] = fun(dat, v)
}
> res
[1] -54 -47 -40 -33 -26 -19 -12 -5 2 9
In this example, k = 10 , but how can I find for every different lists without loop?
I still can't make heads or tails of what you are trying to do, but your code seems to boil down to this:
colSums(matrix(rep(dat,nrow(matrix)),ncol=nrow(matrix)) %*% (matrix*c(1,-1,1)))
That will work for any size of k. It also does not require any of your names.
Some advice: Don't use list when a simple vector will do. You seem to understand how the %*% multiply works, you just need to get your matrices into the right form.