开发者

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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜