开发者

Create a function from an interval

开发者 https://www.devze.com 2023-02-21 01:03 出处:网络
I have this matrix in R, called MRASTI genereatet from the command MRASTI <- matrix(sample(data.matrix(pune, rownames.force=NA),

I have this matrix in R, called MRASTI genereatet from the command

MRASTI <- matrix(sample(data.matrix(pune, rownames.force=NA), 
                        22000, replace=TRUE),
                 nrow=1000, byrow=TRUE)

and i have this interval

x[(x>14274.19)&(x<14458.17)]

which is a vector with 9998 elements. I want to calculate this formula:

y <- 1 / length(MRASTI) * sum((MRASTI - x)^2)

where x takes va开发者_开发知识库lues from the previous interval. How can i do it in R? Thank you

I try this commands:

> for (i in 1:9998) {y<-1/length(MRASTI)*sum((MRASTI-x[i])^2)}

but this generates just a single value Thank you


The problem is with y in this line:

for (i in 1:9998) {
    y <- 1/length(MRASTI)*sum((MRASTI-x[i])^2)
}

At each loop iteration you are overwriting y. The simple solution is:

y <- numeric(length = 9998)
for (i in seq_along(y)) {
    y[i] <- 1 / length(MRASTI) * sum((MRASTI - x[i])^2)
}

Without seeing some example objects and the code to create them and run your code, it is difficult to say if we could vectorise this for you so you don't need a loop.

0

精彩评论

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