简体   繁体   English

在 R 中一起编码和和乘积

[英]Coding a sum and product together in R

I am new to R and I am trying to get some experience coding.我是 R 的新手,我正在尝试获得一些编码经验。 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 :具有“r”-多列和“n”-多行的数据矩阵 (rxn)

x : a vector with "r" many variables x :具有“r”多个变量的向量

l : a vector with "r" many variables l :具有“r”多个变量的向量

z_j : all the values of in the column "j" of the data matrix X z_j :数据矩阵X的“j”列中的所有值

这就是我要编写的代码

This is what I have so far, but it's not giving me the expected output这是我到目前为止所拥有的,但它并没有给我预期的 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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