简体   繁体   English

用户定义函数内部和外部的结果不同,为什么?

[英]Different results inside and outside of a user-defined function,why?

I have a function for calculating an index called 'MCI'. 我有一个用于计算称为“ MCI”的索引的函数。 The codes are 的代码是

mci<-function(Data){
    N<-dim(Data)[1]
    L<-dim(Data)[2]
    r <- rowSums(Data)      
    i.sc <- colSums(Data)       
    r.matrix <- matrix(r,N,1) %*% matrix(1,1,L)
    p.cor.i  <- (i.sc/N)                
    p.cor.i.matrix  <- t(matrix(p.cor.i,L,N))
    gutt <- r.matrix - t(matrix(1:L,L,N))
    gutt<<- ifelse(gutt<0,0,1)
    antigutt <- (L-r.matrix) - t(matrix(1:L,L,N))
    antigutt<<- ifelse(antigutt<0,1,0)
    Covgp<-diag(cov(t(gutt),t(p.cor.i.matrix)))
    Covdp<-diag(cov(t(Data),t(p.cor.i.matrix)))
    Covagp<-diag(cov(t(antigutt),t(p.cor.i.matrix)))
    MCI <- (Covgp-Covdp)/(Covgp-Covagp)
    return(MCI)
}

on a data set like this: 在这样的数据集上:

   V1 V2 V3 V4 V5 V6
1   1  1  1  1  0  1
2   0  0  0  1  0  0
3   1  1  0  1  1  1
4   1  1  1  1  0  1
5   1  0  1  0  0  0
6   1  1  1  1  1  1
7   1  1  1  0  1  1
8   0  1  1  1  1  1
9   1  1  0  1  1  1
10  0  1  1  0  0  0

it returns: 它返回:

[1] Inf Inf Inf Inf Inf Inf Inf Inf Inf Inf

but if I calculate each part of the function independently the result will be: 但是如果我独立计算函数的每个部分,结果将是:

[1] -Inf  NaN  NaN -Inf 0.3333333  NaN  NaN  NaN  NaN 0.0000000

Why this happens and how can I prevent this in future programming? 为什么会发生这种情况?在以后的编程中如何防止这种情况发生?

These lines are the problem: 这些行是问题所在:

gutt<<- ifelse(gutt<0,0,1)

antigutt<<- ifelse(antigutt<0,1,0)

You're assigning to an object in the enclosing environment, and not modifying the object (with the same name) in the function's environment. 您是在封闭环境中分配一个对象,而不是在函数环境中修改该对象(具有相同的名称)。 When you assign to gutt in the first of these lines, it does not affect gutt in the function, that you then use a few lines later. 当您在这些行的第一行中分配给gutt时,它不会影响该函数中的gutt ,因此您稍后再使用几行。

Change these two lines to read: 将这两行更改为:

gutt<- ifelse(gutt<0,0,1)

antigutt<- ifelse(antigutt<0,1,0)

and the function agrees with running the code line-by-line. 并且该功能与逐行运行代码一致。

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

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