Replace Zero and Infinity values in an array (R)

3

In the example matrix below (daily stock returns):

       IBOV        PETR4        VALE5       ITUB4        BBDC4        PETR3
[1,] -0.03981646 -0.027412907 -0.051282051 -0.05208333 -0.047300526 -0.059805285
[2,] -0.03000415 -0.030534351 -0.046332046 -0.03943116 -0.030090271 -0.010355030
[3,] -0.02241318 -0.026650515  0.000000000 -0.04912517 -0.077559462  0.005231689
[4,] -0.05584830 -0.072184194 -0.066126856 -0.04317056 -0.066704036  0.000000000
[5,]  0.01196833 -0.004694836  0.036127168 -0.00591716 -0.006006006  Inf
[6,]  0.02039587  0.039083558  0.009762901  0.01488095  0.024169184  0.011783189

I would like to replace the values 0 (Zero) and Inf by the value of the first column, on the same line as the value 0 or Inf.

Any ideas?

    
asked by anonymous 02.06.2014 / 15:54

3 answers

1

Thanks for the answers, here is a form that was answered in the English stack that worked:

infinite_na is the array with the values of ret == 0, infinity and -1

bancodados_ret is the matrix with the daily returns of stocks and ibovespa

 infinite_na <- bancodados_ret==0 | is.infinite(bancodados_ret)|bancodados_ret==-1
 infinite_na[is.na(infinite_na)]=FALSE
 bancodados_ret[infinite_na] <- bancodados_ret[row(infinite_na)[infinite_na], 1]
    
02.06.2014 / 20:18
1

I think you could do something like this:

ind <- which(my.matrix==0, arr.ind=TRUE)
apply(ind, 1, function(x) my.matrix[x[1], x[2]] <<- my.matrix[x[1], 1])

See if that's what you wanted.

In the code above, I find the row and column of a pattern, and apply a substitution function to the array of indexes. Do not forget to use the global assignment operator " because the apply function applies the function only locally.

    
02.06.2014 / 17:32
1

You can do this as follows. Below m is its parent:

m[m==0] <- m[row(m)[m== 0], 1]
m[is.infinite(m)] <- m[row(m)[is.infinite(m)],1]
    
03.06.2014 / 15:52