1

I have the matrix ABS.Matrix, which contains the absolute valute of a correlation matrix. Dimension of the matrix is 224*224.

For all variables I need to select the name of the first 10 largest correlations.

For a sigle variable I can determine it as follows:

A<-head(colnames(rbind(sort(ABS.Matrix[,2],decreasing=TRUE))),10)
B<-head(colnames(rbind(sort(ABS.Matrix[,224],decreasing=TRUE))),10)

This is for example for variable n.2 e 224.

If I do:

cbind(A,B)

I obtain a matrix where the two columns are the first 10 largest correlation variable names. I need do iterate it and obtain the same results for all the 224 variables.

I have tried:

for (k in 1:224){
  X[k]=head(colnames(rbind(sort(ABS.Matrix[,k],decreasing=TRUE))),10) 
}

to obtain the results for all variables but I get the error "number of items to replace is not a multiple of replacement length".

How I can do that in the correct way? There is easier way?

Angelo
  • 13
  • 2
  • If you add a [minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610) its way easier for others to find a solution to your problem. That way you can help others to help you! – dario Feb 23 '20 at 22:57
  • Thanks Dario! Your solution works fine. For my better understanding and learning which was the issue with my code? – Angelo Feb 24 '20 at 07:25
  • Thats hard to tell because we do not know what `X` is. But if it is a matrix you probsbly should have used X[k, ] or maybe X should be a list... – dario Feb 24 '20 at 11:42

1 Answers1

0

We can simplify and use apply on the columns to get the desired result:

k <- apply(ABS.Matrix, 2, function(x) names(sort(x, decreasing=TRUE))[1:10])

Explanation: For each column in ABS.Matrix we do:

  1. Sort the column in decreasing order
  2. Use names to get the rownames
  3. Select the first 10 elements

The result is a character matrix

Edit:

An example:

1.Create minimal reproducible example data:

set.seed(145)
ABS.Matrix <- matrix(runif(4*4), ncol=4)
rownames(ABS.Matrix) <- paste0("r", 1:4)
colnames(ABS.Matrix) <- paste0("c", 1:4)

Example data:

ABS.Matrix
          c1        c2        c3        c4
r1 0.7539312 0.7042628 0.8561452 0.7011781
r2 0.5340212 0.6432927 0.9614117 0.4876268
r3 0.8568702 0.9716768 0.9147102 0.6565614
r4 0.9237723 0.8538198 0.0656714 0.1375255

2.Use code from above:

k <- apply(ABS.Matrix, 2, function(x) names(sort(x, decreasing=TRUE))[1:2])

k is now:

      c1   c2   c3   c4  
[1,] "r4" "r3" "r2" "r1"
[2,] "r3" "r4" "r3" "r3"
dario
  • 6,415
  • 2
  • 12
  • 26