Comparing matrices of different sizes in R

1

I have the following situation:

all_sec = Matrix of all possible assets in a portfolio

all_sec <- matrix(c("SEC1","SEC2","SEC3","SEC4","SEC5"),ncol=1)

portfolio < - composition of an asset portfolio (column 2 is equal to the weight of the asset in the portfolio

portfolio <- matrix(c("SEC2","SEC4",0.45,0.55),ncol=2)

I want as a result a 1-column matrix in which the value returns 0 if the asset is not in the portfolio and returns the value of the weight (column 2 of the portfolio matrix) if it is in the portfolio. The result would be a matrix in this format:

     [,1]  
[1,] 0
[2,] 0.45
[3,] 0
[4,] 0.55
[5,] 0

Could you help me?

    
asked by anonymous 15.07.2014 / 17:52

3 answers

2

You can do this with merge :

resultado <- merge(all_sec, portfolio, all=TRUE) # faz o merge das duas matrizes
resultado <- apply(resultado, 2, as.character) # transforma em texto de novo (porque o default do R é transformar texto em factor
resultado[is.na(resultado)] <-0 #substitui NA por zero
dimnames(resultado) <- NULL # tira os nomes das dimensões

Then you will get the following result:

resultado
     [,1]   [,2]  
[1,] "SEC1" "0"   
[2,] "SEC2" "0.45"
[3,] "SEC3" "0"   
[4,] "SEC4" "0.55"
[5,] "SEC5" "0"   

And if you only want the second column:

subset(resultado, select=V2)
     [,1]  
[1,] "0"   
[2,] "0.45"
[3,] "0"   
[4,] "0.55"
[5,] "0"   

Now, an important thing to note is that your portfolio array is mixing elements character with numeric so it will turn everyone character . Maybe you should work with data.frame and not an array.

    
16.07.2014 / 04:41
1
#define as matrizes
all_sec <- matrix(c("SEC1","SEC2","SEC3","SEC4","SEC5"),ncol=1)
portfolio <- matrix(c("SEC2","SEC4",0.45,0.55),ncol=2)
#define o tamanho das matrizes (melhor que ficar chamando dim() toda hora)
all_dim <- dim(all_sec)[1]
portfolio_dim <- dim(portfolio)[1]
#cria a matriz para guardar os resultados
resultado <- matrix(data=NA, nrow=all_dim, ncol=1) 
for(j in 1:all_dim){
   #inicia como 0
   resultado[j] <- 0
   #procura por X no portfolio
   for(i in 1:portfolio_dim){
      #se encontrar define o mesmo
      if(all_sec[j] == portfolio[i,1]){
        resultado[j] <- portfolio[i,2]
        break
      }
   }
}
print(resultado)
    
15.07.2014 / 18:41
0

You can do this with the data.table package:

> library(data.table)

> all_sec <- matrix(c("SEC1","SEC2","SEC3","SEC4","SEC5"),ncol=1)
> portfolio <- matrix(c("SEC2","SEC4",0.45,0.55),ncol=2)
> all_sec = data.table(all_sec, key='V1')
> all_sec
     V1
1: SEC1
2: SEC2
3: SEC3
4: SEC4
5: SEC5
> portfolio = data.table(portfolio, key='V1')
> portfolio
     V1   V2
1: SEC2 0.45
2: SEC4 0.55
> portfolio[all_sec]
     V1   V2
1: SEC1   NA
2: SEC2 0.45
3: SEC3   NA
4: SEC4 0.55
5: SEC5   NA

> as.matrix(portfolio[all_sec][, list(V1, V2=as.numeric(as.character(V2)))][is.na(V2), V2 := 0][, V2])
     [,1]
[1,] 0.00
[2,] 0.45
[3,] 0.00
[4,] 0.55
[5,] 0.00
> 
    
17.07.2014 / 03:48