• R语言
  • 求教一个apply函数的问题

想要对不同的值赋上不同的颜色

eg. <=50的值 赋上grey(0.8)...以此类推

runif(n=50,min=40,max=90)->S

apply(as.matrix(S),1,function(x){

if(x<=50){x<-grey(0.8)}

else if(x<=60){x<-grey(0.6)}

else if(x<=70){x<-grey(0.4)}

else if(x<=80){x<-grey(0.2)}

else if(x<=90){x<-grey(0.1)}

else x<-NA

}

但是这个apply函数却跑不出来~ 请教诸位大神问题出在哪里?

换成for循环之后又能够跑出来。

for (i in 1:length(S)){

S->x

if(x<=50){S<-grey(0.8)}

else if(x<=60){S<-grey(0.6)}

else if(x<=70){S<-grey(0.4)}

else if(x<=80){S<-grey(0.2)}

else if(x<=90){S<-grey(0.1)}

else S<-NA

}


搞得很confusing~~~~~~


一个向量没必要用apply 可以用5个which取下标再赋值