If there is a sequence of x_i and y_i for i=1, ..., I. How to write a summation of \sum_{k\neq i} x_{k}y_{K} in R where the index is the summation over k except for a fixed i? I am writing a for loop:
for (i in 1:I){ sum(x*y)???
}
If there is a sequence of x_i and y_i for i=1, ..., I. How to write a summation of \sum_{k\neq i} x_{k}y_{K} in R where the index is the summation over k except for a fixed i? I am writing a for loop:
for (i in 1:I){ sum(x*y)???
}
Start by defining an exclude vector.
Then remove those values i from i_vals with the - operator, leave an include vector.
# example data
set.seed(1L)
I <- 10
i_vals <- 1:I
x <- rnorm(I)
y <- rnorm(I)
exclude <- c(3, 6)
include <- i_vals[-exclude] # 1 2 4 5 7 8 9 10
Now you have a few options for how to perform your desired operation.
The fastest approach is to use R's %*% dot product operator:
x[include] %*% y[include] # -3.057424
Alternates:
i values for x with their corresponding values include values in y, and sum.sum(x[include] * y[include]) # -3.057424
products <- vector(length = I)
for (i in include) products[i] <- x[i] * y[i]
sum(products) # -3.057424
Try this:
I=5
set.seed(1)
x <- runif(I)
set.seed(2)
y <- runif(I)
n <- NULL
for (i in 1:I) n[i] <- sum(x[-i]*y[-i])
data.frame(x,y,n)
# x y n
# 1 0.2655087 0.1848823 0.9327835
# 2 0.3721239 0.7023740 0.7205012
# 3 0.5728534 0.5733263 0.6534394
# 4 0.9082078 0.1680519 0.8292453
# 5 0.2016819 0.9438393 0.7915160