Vectorize my thinking: Vector Operations in R

前端 未结 3 1784
醉酒成梦
醉酒成梦 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 09:55

    Here's what seems like another very R-type way to generate the sums. Generate a vector that is as long as your input vector, containing nothing but the repeated sum of n elements. Then, subtract your original vector from the sums vector. The result: a vector (isums) where each entry is your original vector less the ith element.

    > (my.data$item[my.data$fixed==0])
    [1] 1 1 3 5 7
    > sums <- rep(sum(my.data$item[my.data$fixed==0]),length(my.data$item[my.data$fixed==0]))
    > sums
    [1] 17 17 17 17 17
    > isums <- sums - (my.data$item[my.data$fixed==0])
    > isums
    [1] 16 16 14 12 10
    

提交回复
热议问题