r语言程序,矢量化功能问题

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)

val.pos<-which(x==val)

b)

monotonic<-mean(diff(x)>0)==1 || mean(diff(x)<0)==1

或者这样做(应该更稳健,但是有点作弊嫌疑)

monotonic<-!(is.unsorted(x,na.rm=TRUE,strictly=TRUE) &&
            is.unsorted(rev(x),na.rm=TRUE,strictly=TRUE))

温馨提示:答案为网友推荐,仅供参考