Replace Zero and Infinity values in a matrix (R)

Asked

Viewed 1,031 times

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 in the same row as 0 or Inf.

Any idea ?

  • Just so I’m clear, you want to trade 0 or infinity for the Ibovespa values?

  • I want to exchange the 0 and Infinitos for the values of the Ibovespa on the same day. For example Vale5 in row 3 would be -0.022413418 The PETR3 in row 5 would be 0.01196833

3 answers

1

You can do it as follows. Below m is your matrix:

m[m==0] <- m[row(m)[m== 0], 1]
m[is.infinite(m)] <- m[row(m)[is.infinite(m)],1]

1

I think you could do something like:

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 this is what you really wanted.

In the code above, I discover the row and column of a pattern, and apply a substitution function to the index matrix. Do not forget to use the global assignment operator "<-" because the function apply apply the function only locally.

1


Thanks for the answers, follows a form that was answered in the stack in English that worked too :

infinite_na is the matrix with values of Ret == 0, infinity and -1

bancodados_ret is the matrix with the daily returns of shares 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]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.