[R] Function returns different results on the vector as a whole vs. on the values of the vector
Corrado
ct529 at york.ac.uk
Tue Sep 15 18:26:43 CEST 2009
Dear R friends,
I have developed the function here below attached.
Strangely, when I apply it to a vector it behaves very differently than when I
apply it separately to each value of the vector itself.
Is there any reason why?
Here is the function:
# TODO: Add comment
#
# Author: ct529, 3 Sep 2009, 08:42:50,mspline.R
###############################################################################
mspline<-function(i=1,x=0,k=1,t=c(0,1)){
# x is the variable
# i is the index of the member of the Mspline family
# t is the vector of knots. t[h] is the h-th knot.
# k is the Mspline degree
I<-i
if(identical(k,1)){
if( x<t[i+1] && x>=t[i] ){
td<-t[i+1]-t[i]
M<-1/td
}else{
M<-0
}
}else if (k>1) {
kk<-(k-1)
if (x>=t[i] && x<t[i+k]){
M<-k*((x-t[i])*mspline(i=I,x=x,k=kk,t=t)+(t[i+k]-
x)*mspline(i=(I+1),x=x,k=kk,t=t))/((k-1)*(t[i+k]-t[i]))
} else if (x<t[i] || x>=t[i+k]){
M<-0
}
}
return(M)
}
For example:
source("./functions/mspline.R")
X<-seq(0,1,0.1)
Q<-c(0,0,0,0.3,0.5,0.6,1,1,1)
II<-c(1,2,3,4,5,6)
plot(c(0,1),c(0,24),type="p",col="white",cex=".4",pch=".")
for (h in II) {
y<-vector()
for (xxxx in X) {
y<-append(y,mspline(i=h,x=xxxx,k=3,t=Q))
}
points(X,y,type="l",col="green")
}
works very differently from using a vectorial approach, that is substituting
the inner for iteration with the expression:
y<-mspline(i=h,x=X,k=3,t=Q)
Regards
--
Corrado Topi
Global Climate Change & Biodiversity Indicators
Area 18,Department of Biology
University of York, York, YO10 5YW, UK
Phone: + 44 (0) 1904 328645, E-mail: ct529 at york.ac.uk
More information about the R-help
mailing list