Vectorize my thinking: Vector Operations in R

前端 未结 3 1783
醉酒成梦
醉酒成梦 2020-12-24 09:30

So earlier I answered my own question on thinking in vectors in R. But now I have another problem which I can\'t \'vectorize.\' I know vectors are faster and loops slower, b

3条回答
  •  臣服心动
    2020-12-24 10:03

    Strangely enough, learning to vectorize in R is what helped me get used to basic functional programming. A basic technique would be to define your operations inside the loop as a function:

    data = ...;
    items = ...;
    
    leave_one_out = function(i) {
       data1 = data[items != i];
       delta = ...;  # some operation on data1
       return delta;
    }
    
    
    for (j in items) {
       delta.list = cbind(delta.list, leave_one_out(j));
    }
    

    To vectorize, all you do is replace the for loop with the sapply mapping function:

    delta.list = sapply(items, leave_one_out);
    

提交回复
热议问题