Home > Blockchain >  Coding a sum and product together in R
Coding a sum and product together in R

Time:08-04

I am new to R and I am trying to get some experience coding. I have quite a large program but I can't seem to figure out how to code the following. Any help would be greatly appreciated

X: a data matrix with "r"-many columns and "n"-many rows (r x n)

x: a vector with "r" many variables

l: a vector with "r" many variables

z_j: all the values of in the column "j" of the data matrix X

This is what I am trying to code

This is what I have so far, but it's not giving me the expected output

X<-matrix(c(0,1,2,1,2,4), ncol = 2)
x<-numeric()
x[1] <- 2
x[2] <- 5
l<-numeric()
l[1] <- 0.5
l[2] <- 0.5
   for (j in 1:ncol(X)){
    for (i in 1:nrow(X)){
      mean(prod((l[j]^(abs(X[i,j]-x[j])))/sum(l[j]^(abs(X[i,j]-X[1:nrow(X),j])))))
    }    
  }

CodePudding user response:

You're never aggregating up the product and sum; but your formula looks right enough.

If you follow your notation a bit more closely and break it up; I think it is easier to follow.

# Create toy data
n <- 10
r <- 5
X <- matrix(runif(r*n), n, r)

x <- runif(r)
l <- runif(r)

# Making the sum
summand <- 0
for (i in seq_len(n)) {
  product <- 1
  for (j in seq_len(r)) {
     top <- l[j]^abs(X[i, j] - x[j])
     bot <- sum(l[j]^abs(X[i, j] - X[, j]))
     product <- product*top/bot
  }
  summand <- summand   product/n
}

print(summand)
# [1] 4.709275e-05

This can probably be made much more efficient using proper vectorization. Anyway, on you data, I get:

print(summand)
#[1] 0.07704795
  • Related