[R] Can't get function to run iteratively
Dimitris Rizopoulos
dimitris.rizopoulos at med.kuleuven.ac.be
Fri Apr 8 12:33:42 CEST 2005
R is a vectorized language, look at this:
fd <- function(b, gn, ..., eps=sqrt(.Machine$double.neg.eps)){
n <- length(b)
g0 <- gn(b, ...)
out <- numeric(n)
b. <- b + eps*max(abs(b), 1)
c(gn(b., ...) - g0) / (b. - b)
}
##############
test <- function(x) x*x
fd(seq(0.1, 0.5, 0.1), test)
2*seq(0.1, 0.5, 0.1)
I hope it helps.
Best,
Dimitris
----
Dimitris Rizopoulos
Ph.D. Student
Biostatistical Centre
School of Public Health
Catholic University of Leuven
Address: Kapucijnenvoer 35, Leuven, Belgium
Tel: +32/16/336899
Fax: +32/16/337015
Web: http://www.med.kuleuven.ac.be/biostat/
http://www.student.kuleuven.ac.be/~m0390867/dimitris.htm
----- Original Message -----
From: "Uzuner, Tolga" <tolga.uzuner at csfb.com>
To: <r-help at stat.math.ethz.ch>
Sent: Friday, April 08, 2005 12:08 PM
Subject: [R] Can't get function to run iteratively
> Trying to do something very simple...
>
>> numerical.grad
> function(func,x, eps=1e-12) {
> # very simple (crude) numerical approximation
> f <-func(x)
> df <-1:length(x)
> for (i in 1:length(x)) {
> dx <- x
> dx[i] <- dx[i] +eps
> df[i] <- (func(dx)-f)/eps
> }
> df
> }
>> test<-function(x){x^2}
>> y<-seq(0.1,0.5,0.1)
>> numerical.grad(test,y)
> [1] 0.1999997 0.0000000 0.0000000 0.0000000 0.0000000
> Warning messages:
> 1: number of items to replace is not a multiple of replacement
> length
> 2: number of items to replace is not a multiple of replacement
> length
> 3: number of items to replace is not a multiple of replacement
> length
> 4: number of items to replace is not a multiple of replacement
> length
> 5: number of items to replace is not a multiple of replacement
> length
>>
>
>
> Any thoughts why this doesn't seem to be working ?
>
>
> ==============================================================================
> This message is for the sole use of the intended recipient. If you
> received
> this message in error please delete it and notify us. If this
> message was
> misdirected, CSFB does not waive any confidentiality or privilege.
> CSFB
> retains and monitors electronic communications sent through its
> network.
> Instructions transmitted over this system are not binding on CSFB
> until they
> are confirmed by us. Message transmission is not guaranteed to be
> secure.
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
>
More information about the R-help
mailing list