[R] What's wrong with my code?

Berend Hasselman bhh at xs4all.nl
Sun Aug 12 06:18:03 CEST 2012


stephenxqy wrote
> 
> It is a complex function, functions are quoted frequently, you may read
> from bottom up
> The independent variable for final fit is q
> 
> %%Rg0 is a function of L and b
> Rg0sq<-function(L,b)L*b/6*(1-3/2*b/L+3/2*(b/L)^2-3/4*(b/L)^3*(1-exp(-2*L/b)))
> 
> %%alpha is a defined function
> alpha<-function(x)(1+(x/3.12)^2+(x/8.67)^3)^(0.176/3)
> 
> %%w is a defined function
> w<-function(x)(1+tanh(x-1.523)/0.1477)/2
> 
> %%It is Rg^2
> Rgsq<-function(L,b)(alpha(L/b)*Rg0sq(L,b))
> 
> %%This is Rg
> Rg<-function(L,b)(Rg0sq(L,b))^0.5
> 
> %%A debye function of q, the parameters are L and b
> PDebye<-function(L,b)2*(exp(-q^2*Rg0sq(L,b))+q^2*Rg0sq(L,b)-1)/q^4/(Rg0sq(L,b))^2
> 
> %%Another function of q that quote w, PDebye, Rg, parameters are v, L and
> b
> Pexv<-function(v,L,b)w(q*Rg(L,b))*PDebye(L,b)+(1-w(q*Rg(L,b)))(1.22*(q*Rg(L,b))^(-1/v)+0.4288*(q*Rg(L,b))^(-2/v)-1.651*(q*Rg(L,b))^(-1/v))
> 
> %%Another defined function
> cf<-function(L,b,pa,pb)pa/(L/b)^pb
> 
> %%A function of q, quote Pexv, Rgsq, cf
> Psfcex<-function(v,L,b,pa,pb)Pexv(v,L,b)+cf(L,b,pa,pb)*b/L/15*(4+7/q^2/Rgsq(L,b)-(11+7/q^2/Rgsq(L,b))*exp(-q^2*Rgsq(L,b)))
> 
> %%non-linear fit
> Pfit<-function(p)sum((I-Psfcex(p[1],p[2],p[3],p[4],p[5]))^2)
> wavefit<-nlm(Pfit,c(1.5,500,5,1,0.1),hessian=TRUE)
> 
> error code: Error in c(1.5, 500, 5, 1, 0.1) : unused argument(s) (0.1)
> the fifth parameter is pb, which goes from Psfcex to cf, actually pa which
> only exist in cf is used, why not pb?
> 

1. What language is this? # starts a comment line in R not %%.
2. no data for q
3. what is I in Pfit?
4. Pexv: missing * or + or ... The expression in the function Pexv should
probably read

   
w(q*Rg(L,b))*PDebye(L,b)+(1-w(q*Rg(L,b)))*(1.22*(q*Rg(L,b))^(-1/v)+0.4288*(q*Rg(L,b))^(-2/v)-1.651*(q*Rg(L,b))^(-1/v)) 

I have inserted  * after    (1-w(q*Rg(L,b))) assuming that is what you want.

Your code is not reproducible since you have not provided data for q or I.
Generating some random data and assuming I is an identity matrix with 

set.seed(123)
q <- rnorm(20) + 5 
I <- diag(length(q))

adding wavefit at the end of the script and changing the %% to # your script
runs with no errors but with warnings.
So I can't tell you why you  get the error message you got.

Finally: this is very inefficient code. There are repeated evaluations of
same thing e.g. w(q*Rg(L,b)), Rg(L,b), Rg0sq(L,b) etc.

Berend





--
View this message in context: http://r.789695.n4.nabble.com/What-s-wrong-with-my-code-tp4640034p4640077.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list