Abe Miessler
Abe Miessler

Reputation: 85116

How to replace indices with actual values?

Say I have the following data:

         [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
   [1,]  983  362  170  303  914  843  480  489  474   355
   [2,]  204  205  810  762  758  404   24  111  265   586

Each of these values corresponds to an index in another set called labels. I would like to create the exact same structure as above, but instead of having the index, I want the value.

So far I have tried:

labels[attr(k,"nn.index")[1,]]

which returns [1] 2 2 2 2 2 2 2 2 2 2, my desired result for the first row, and:

labels[attr(k,"nn.index")[2,]]

which returns [1] 0 0 0 0 0 0 0 0 0 0, my desired result for the second row.

My problem is that if I try to do this for all rows I get the following results:

labels[attr(k,"nn.index")[1:2,]]
 [1] 2 0 2 0 2 0 2 0 2 0 2 0 2 0 2 0 2 0 2 0

What would I have to change to get the result below?

         [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
   [1,]   2    2    2    2    2    2    2    2    2    2
   [2,]   0    0    0    0    0    0    0    0    0    0

Also, in real life there are thousands of rows, not just two.

Upvotes: 1

Views: 197

Answers (1)

David Robinson
David Robinson

Reputation: 78620

Do:

apply(attr(k,"nn.index"), 2, function(col) labels[col])

But didn't I give you this precise answer in your previous question? (See the closest.labels variable).

Upvotes: 3

Related Questions