开发者

Vectorizing a loop in R

开发者 https://www.devze.com 2023-01-25 10:34 出处:网络
There must be a simple way to vectorize the following loop in R, but I can\'t see it. w <- numeric(10)

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

精彩评论

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