0

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)???
  }
Hermi
  • 357
  • 1
  • 11
  • 2
    Just to avoid confusion and to [make your problem reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example), can you add a minimal working example and expected output (5 values each should be fine). – markus Nov 23 '20 at 16:40
  • also good to specify whether the `i` to skip is constrained to a single value or could take multiple values in `I`. – andrew_reece Nov 23 '20 at 16:42

2 Answers2

1

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:

  1. Use vectorized multiplication: multiply all of the included i values for x with their corresponding values include values in y, and sum.
sum(x[include] * y[include]) # -3.057424
  1. Use a for-loop, as in your initial approach:
products <- vector(length = I)

for (i in include) products[i] <- x[i] * y[i]

sum(products) # -3.057424
andrew_reece
  • 20,390
  • 3
  • 33
  • 58
0

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
Marcos Pérez
  • 1,260
  • 2
  • 7
  • Thanks for your solution. But how about two index summations? If x is a 5 by 5 matrix. Can we still have `x[i,-j]` if fix `i` and exclude `j` for each summation? – Hermi Nov 25 '20 at 14:00
  • Why there is an Error in x[i, -j] : subscript out of bounds? – Hermi Nov 25 '20 at 14:01
  • Hi, you must put the row index first x[-j,i] – Marcos Pérez Nov 25 '20 at 14:12
  • Can you help me see this question: https://stackoverflow.com/questions/65006553/how-to-compute-the-following-exclude-an-index-summation-in-r? Thank you. – Hermi Nov 25 '20 at 14:22