Vectorizing a loop in R
There must be a simple way to vectorize the following loop in R, but I can't see it.
w <- numeric(10)
z <- rnor开发者_运维技巧m(20)
v <- c(sample(1:10,10),sample(1:10,10)) #Random ordering of c(1:10,1:10)
for(i in 1:10)
w[i] <- sum(z[v==i])
another approach
w = rowsum(z, v)
You could use aggregate:
aggregate(z, by=list(v), sum)
精彩评论