I am currently writing a program in R to find solutions of a general polynomial difference equation using Picard's method.
For an insight in the mathematics behind it (as math mode isn't available here):
https://math.stackexchange.com/questions/2064669/picard-iterations-for-general-polynomials/2064732
Now since then I've been trying to work with the Ryacas package for integration. However I ran into trouble trying to work with the combination of expression and integration function.
library(Ryacas)
degrees = 3
a = c(3,5,4,6)
x0 = -1
maxIterations(10)
iteration = vector('expression', length = maxIterations)
iteration[1] = x0
for(i in 2:maxIterations){
for(i in 1:degrees){
exp1 = expression( a[i] * iteration[i-1] ^ i)
}
iteration[i] = x0 + Integrate(exp1, t)
}
but this results in
"Error in paste("(", ..., ")") :
cannot coerce type 'closure' to vector of type 'character'"
and exp1 = expression(a[j] * iteration[i-1]^j) instead of an actual expression as I tried to achieve. Is there anyway I can make sure R reads this as a real expression (i.e. for example 3 * ( x0 ) ^ j for i = 2)?
Thanks in advance!
Edit:
I also found the Subst() function, and currently trying to see if anything is fixable using it. Now I am mainly struggling to actually set up an expression for m coefficients of a, as I can't find a way to create e.g. a for loop in the expression() command.
Related
How can we numerically solve these equations using R when E_(μ,σ) (X)=1 and 〖var〗_(μ,σ) (X)=1 ? I am interested in finding the values of μ and σ.
Here α=(a-μ)/σ and β=(b-μ)/σ. I used the following code, but I'm not getting an answer. Is there any other code or method I may use to get what I want ?
mubar<-1
sigmabar<-1
a<-0.5
b<-5.5
model <- function(x)c(F1 = mubar-x[1]+x[2]*((pnorm((b-x[1])/x[2])-pnorm(a-x[1])/x[2])/(dnorm((b-x[1])/x[2])-dnorm((a-x[1])/x[2]))),
F2 = sigmabar^2-x[2]^2*(1-(((b-x[1])/x[2]*pnorm((b-x[1])/x[2])-(a-x[1])/x[2]*pnorm((a-x[1])/x[2]))/(dnorm((b-x[1])/x[2])-dnorm((a-x[1])/x[2])))-((pnorm((b-x[1])/x[2])-pnorm((a-x[1])/x[2]))/(dnorm((b-x[1])/x[2])-dnorm((a-x[1])/x[2])))^2) )
(ss <- multiroot(f = model, start = c(1, 1)))
I want to be able to find the anti-derivative of an arbitrary function in R.
Suppose I´ve got f = 1/(2*x^2) and want to find F, which by the way is easy to calculate by hand.
I´ve tried the following:
f<- function (x) {1/(sqrt(x))}
F = antiD(f)
This gives me:
Error: no applicable method for 'rhs' applied to an object of class "function"
Can someone give me a push in the right direction here?
Are you using the mosaicCalc package?
I don't think you can use a function as argument to the antiD(). It expects a formula:
F <- antiD( 1/sqrt(x) ~ x)
This will give you a function F that takes two parameters x and C (constant). In this instance, it can't do a symbolic integration as it doesn't know what to do with the sqrt() function. If you alternatively did:
F <- antiD(x^-0.5 ~ x)
Then you'll see that symbolic integration has been done:
F
function (x, C = 0) {2 * x^(1/2) + C}
With Ryacas:
library(Ryacas)
yac_str("Integrate(x) 1/Sqrt(x)")
# [1] "2*Sqrt(x)"
I am trying to find parameters using the nls2 package. As the formula I am trying to optimize parameters for is quite complex, I try to use functions that I call within the formula I optimize with the nls2 command:
library(nls2)
set.seed(20160227)
x <- seq(0,50,1)
y <- ((runif(1,10,20)*x)/(runif(1,0,10)+x))+rnorm(51,0,1)
a <- function(){
d+1
}
f1 <- function(){
y <- a()*x/(b+x)
}
st <- data.frame(d = c(-100,100),
b = c(-100,100))
nls2(f1,start = st, algorithm = "brute-force")
Currently, this throws the error
Error: object of type 'closure' is not subsettable
I found this error here, however when I assign values to b and d this works:
a()*x/(b+x)
I assume the problem is that I try to find b and d using functions that already have them inside?
What is the best way to do this? Is it even possible or do I need to define the entire complex formula within nls2?
Neither f1 nor a here have any parameters, so it's not really surprising that it's having some difficulty understanding how you want to optimize f1.
nls2::nls2 (like stats::nls) expects a formula as the first parameter. That formula can be built from any function you want, and does not have to be written down entirely in the call. You could do the following:
a <- function(d){
d+1
}
f1 <- function(b,d,x){
y <- a(d)*x/(b+x)
}
And then fit the model like this:
nls2(y~f1(b,d,x), start = st, algorithm = "brute-force")
Because no start value is provided for x, and because its actual value can be found in the environment, it won't optimize over x, just b and d.
First thing's first; my skills in R are somewhat lacking, so there is a chance I may be using something incorrectly in the following. If I go wrong somewhere, please let me know.
I've been having a problem in Rstudio where I try to create 2 functions for formulae, then use nls() to create a model using those, with which I will make a plot. When I try to run the line for creating it, I get an error message saying an object is missing. It is always the last object in the function of the first "formula", in this case, 'p'.
I'll provide my code here then explain what I am trying to do for a little context;
DATA <- read.csv(file.choose(), as.is=T)
formula <- function(m, h, g, p){(2*m)/(m+(sqrt(m^2+1)))*p*g*(h^2/2)}
formula.2 <- function(P, V, g){P*V*g}
m = 0.85
p = 766.42
g = 9.81
P = 0.962
h = DATA$lithothick
V = DATA$Vol
fit.1 <- nls(formula (P, V, g) ~ formula(m, h, g, p), data = DATA)
If I run it how it is shown, I get the error;
Error in (2 * m)/(m + (sqrt(m^2 + 1))) * p : 'p' is missing
However it will show h if I rearrange the objects in the formula to (m,g,p,h)
Error in h^2 : 'h' is missing
Now, what I'm trying to do is this; I have a .csv file with 3 thicknesses (0.002, 0.004, 0.006 meters) and 3 volumes (10, 25, 50 milliliters). I am trying to see how the rates of strength and buoyancy increase (in relation to each other) as the thickness and volume for each object (respectively) increases. I was hoping to come out with a graph showing the upward trend for each property (strength and buoyancy), as I believe them to be unequal (one exponential the other linear). I hope that isn't more confusing than clarifying, but any pointers would be GREATLY appreciated.
You cannot overload functions this way in R, what you can do is provide optional arguments (which is a kind of overload) with syntax function(mandatory, optionnal="")
For what you are trying to do, you have to use formula.2 if you want to use the 3-arguments formula.
A workaround could be to use one function with one optionnal argument and check if this argument has been used. Something like :
formula = function(m, h, g, p="") {
if (is.numeric(p)) {
(2*m)/(m+(sqrt(m^2+1)))*p*g*(h^2/2)
} else {
m*h*g
}
}
This is ugly and a very bad way to do it (your variables do not really mean the same thing from one call to the other) but it works.
Suppose I want to integrate some function that involves sums and products of a few other user defined functions. Lets take an extremely simple example, it gives the same error.
integrate(f = sin + cos, lower=0, upper=1)
This yields "Error in sin + cos : non-numeric argument to binary operator" which I think is saying it doesn't make sense to just add functions together without passing them some sort of argument. So I am a bit stuck here. This thread poses what I think is a solution to a more complicated question, that can be applied here, but it seems long for such a simple task in this case. I'm actually kind of surprised that I am unable to find passing function arguments to functions in the help manual so I think I am not using the right terminology.
Just write your own function:
> integrate(f = function(x) sin(x) + cos(x), lower=0, upper=1)
1.301169 with absolute error < 1.4e-14
In this example I've used an anonymous function, but that's not necessary. The key is to write a function that represents whatever function you want to integrate over. In this case, the function should take a vector input and add the sin and cos of each element.
Equivalently, we could have done:
foo <- function(x){
sin(x) + cos(x)
}
integrate(f = foo, lower=0, upper=1)
This is an old question, but I recently struggled with it, so here is a simple example in case it helps others in the future. #joran's answer is still the best.
Define your first function: f1 <- function(x){return(x*2)}
Test it: f1(8) (expect 8*2=16); returns [1] 16
Define your second function: f2 <-function(f, y){return(f+y)}
Test it: f2(f=f1(8), y=1) (expect 8*2 = 16 +1 = 17); returns [1] 17