[R] apply and cor()

Micha Silver tsvibar at gmail.com
Fri May 12 16:57:34 CEST 2017


I have two data.frames, one with a single row of 31 columns, and the 
second with 269 rows and the same 31 columns.
 > dim(compare_data)
[1] 269  31
 > dim(test_data)
[1]  1 31

I want to apply cor() between the one row of 'test_data', and each row 
of the 'compare_data' .
I tried 'apply' but I get this error:
 > apply(compare_data, 1, function(r) {cor(compare_data[r,], test_data)})
  Error in cor(compare_data[r, ], test_data) : incompatible dimensions


In order to try to understand I did:
 > dims <- apply(compare_data, 1, function(r) {dim(compare_data[r,])})
 > head(dims)
      20 73 103 118 130 142 151 154 191 205 217 222 227 232 240 275 282 
301 320 359 360 551 589 653 789 801 808 812
[1,]  9  8   8   9   5   9   8  11   6  15  12  13  10   7   9  14 8  
11   9  11  11  12   9  14   5   8   9  10
[2,] 31 31  31  31  31  31  31  31  31  31  31  31  31  31  31  31 31  
31  31  31  31  31  31  31  31  31  31  31
      840 856 857 867 885 970 983 985 1103 1107 1197 1207 1237 1262 1279 
1282 1332 1357 1358 1392 1411 1435 1458 1473
[1,]  14  11  12   8  10   2   7   9   10    8   10   13   11 7    9   
12   11   11   16   10   10   12   10   10
[2,]  31  31  31  31  31  31  31  31   31   31   31   31   31   31 31   
31   31   31   31   31   31   31   31   31

and indeed I am getting different row dimensions. I expected "1 31" for 
each. What are the values 9,8,8,9,5... in the [1,] dimension?

If I test the compare_data data.frame one row at a time:
 > dim(compare_data['20',])
[1]  1 31
 > dim(compare_data['1473',])
[1]  1 31

It looks as I expected.
What am I missing??

Thanks

-- 
Micha Silver
cell: +972-523-665918



More information about the R-help mailing list