繁体   English   中英

有人可以向我解释我在 R 中的问题吗

[英]Can someone explain to me the problem with my sum in R

对于给定的矩阵 FI 想要计算其行的 2 范数之和,所以我使用 function sum()但它不起作用,因为我希望它在这里做一个例子

# The matrix F
> F <- matrix(c(9,1,1,1,4,1),nrow=3)
# index of the sum i
> i=1:NROW(F)
#And here is the result 
> sum(norm(F[i,], type = "2")^4)
  [1] 7376.60160040254
# and if i calculate each element of the sum i get
> norm(F[1,], type = "2")^4
  [1] 6724
> norm(F[2,], type = "2")^4
  [1] 289
> norm(F[3,], type = "2")^4
  [1] 4

我认为您正在寻找apply function。它沿矩阵的维度应用 function。

sum(apply(F,MARGIN = 1,function(x){norm(x,type = "2")^4}))
#[1] 7017

您的原因不起作用是因为您将c(1,2,3)分配给了i 然后,当您子集F时,您只会得到整个矩阵。

i=1:NROW(F)
i
#[1] 1 2 3
norm(F,type="2")^4
#[1] 7376.602
norm(F[1:3,],type="2")^4
#[1] 7376.602
norm(F[i,],type="2")^4
#[1] 7376.602

免责声明:我没有评估这种方法的数学有效性,只是以编程方式重新创建了 OP 的期望行为。

暂无
暂无

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

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