简体   繁体   中英

Coding a sum and product together in R

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 (rxn)

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 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])))))
    }    
  }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM