Provide avectorized solution that replaces the entire expression in these function by aone line expression that does not use loop. You can assume x is a numeric vector and valis a single numeric value.
a) val.positions<-function(x,val)
{
val.pos<-NULL
for(i in 1:length(x) )
if (x[i]==val) val.pos<-c(val.pos,i)
val.pos
}
b) monotonic<-function(x)
{ monotonic.increasing<-TRUE
monotonic.decreasing<-TRUE
for(iin 2:length(x)) if(x[i]-x[i-1]<0) monotonic.increasing<-FALSE
for(i in 2:length(x)) if(x[i]-x[i-1]>0)monotonic.decreasing<-FALSE
monotonic.increasing | monotonic.decreasing
}
哪位热心的网友能给出解答或者思路,万分感谢。
a)
b)
monotonic<-mean(diff(x)>0)==1 || mean(diff(x)<0)==1
或者这样做(应该更稳健,但是有点作弊嫌疑)
monotonic<-!(is.unsorted(x,na.rm=TRUE,strictly=TRUE) &&