开发者

R or MATLAB - Matching column name to modify the corresponding cell in a matrix

开发者 https://www.devze.com 2023-02-21 19:05 出处:网络
I would like to convert the column wit开发者_JS百科h NODE as header in a Matrix below to their corresponding Gene as follows:

I would like to convert the column wit开发者_JS百科h NODE as header in a Matrix below to their corresponding Gene as follows:

   NODE Gene1 Gene2 Gene3 Gene4 Gene5 NODE1 NODE2 NODE3
1 NODE1  0.98  0.98    NA    NA    NA    NA    NA    NA
2 NODE2    NA    NA   0.8   0.8    NA    NA    NA    NA
3 NODE3    NA    NA    NA    NA  0.72  0.72    NA    NA
4 NODE4    NA    NA    NA    NA    NA    NA   0.6   0.6

As

NODE1 = Gene1 and Gene2
NODE2 = Gene3 and Gene4
NODE3 = Gene5 and NODE1 = Gene5 and Gene 1 and Gene2

I would like to move cells in NODE1 NODE2 and NODE3 columns to their corresponding Gene colunms to output a file like this:

   NODE Gene1 Gene2 Gene3 Gene4 Gene5 
1 NODE1  0.98  0.98    NA    NA    NA    
2 NODE2    NA    NA   0.8   0.8    NA    
3 NODE3  0.72  0.72    NA    NA  0.72    
4 NODE4  0.6   0.6     NA   0.6  0.6  

Are there any methods of doing this? Can I use R or MATLAB to do this?

Best regards,

Catherine


In Matlab you can do it like this:

    clear all
    nrgenes=5;
    nrnodes=4;
    matrix=zeros(nrnodes,nrgenes+nrnodes);
    matrix(1,1:2)=0.98;
    matrix(2,3:4)=0.8;
    matrix(3,5:6)=0.72;
    matrix(4,7:8)=0.6;

    for i=1:nrnodes
        for j=nrgenes+1:nrgenes+nrnodes
            if (matrix(i,j)~=0)
                matrix(i,1:nrgenes)=matrix(i,1:nrgenes)+matrix(i,j)*logical(matrix(j-nrgenes,1:nrgenes));
            end
        end
    end
    result=matrix(1:nrnodes,1:nrgenes);

Some caveats:

  • You maybe have to run this twice to expand all the entries depending on the configuration of entries, but I think you get the idea how to do this from the code.

  • there's a slight error in the Node4 line of your example result.

  • This is coded with two nested for loops. Slow and inefficient for large matrices, but easier to understand. You maybe have to vectorize for large matrices to improve execution time.

0

精彩评论

暂无评论...
验证码 换一张
取 消