Amin
Amin

Reputation: 368

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

I have a function for calculating an index called '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?

Upvotes: 0

Views: 100

Answers (1)

Matthew Lundberg
Matthew Lundberg

Reputation: 42689

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.

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.

Upvotes: 1

Related Questions