Mine
Mine

Reputation: 861

Can't add numbers at a specific index to a double in R

I want create 10 b1's for each value of x1 and x2's in xp and yp lists by optimizing res formula below. However my values are somehow not added to b1.created. I get b1.created = 0 when I check after I run the code.How can I make the code work?

y <- matrix(c(1,2,3,4,2,6,7,8,9,10),ncol = 1)
x1 <- matrix(c(2,4,6,5,10,12,14,16,18,20),ncol =1)
x2 <- matrix(c(1,4,9,16,25,25,48,64,81,99),ncol = 1)
x <- cbind(x1,x2)
created.b1 = 0
normal <- function(b0,y,xp,yp,x1,x2){for (i in xp){
  res <- sum((y- (b0 + x1[i]*xp[i] + x2[i]*yp[i]))^2)
  optobj <- optimize(normal,c(-10,10),y =y ,xp = xp,yp =yp, x1 = x1,x2 = x2)
  created.b1[i] = obtobj$minimum[i]
}
}

Upvotes: 0

Views: 45

Answers (1)

yarnabrina
yarnabrina

Reputation: 1656

I think this does what you want, but please cross-check.

created.b1 <- numeric(length = 10)
for (i in 1:10)
{
    opt_obj <- optimise(f = function(b0, y, xp, yp, x1, x2) sum((y - (b0 + (x1 * xp) + (x2 * yp))) ^ 2),
                        interval = c(-10, 10),
                        y = y,
                        xp = xp[i],
                        yp = yp[i],
                        x1 = x1,
                        x2 = x2)
    created.b1[i] <- opt_obj$minimum
}
created.b1

Upvotes: 1

Related Questions