I have the following code with uses the FNN Package:
k <- knn(train, test, labels, k = 10, algorithm="cover_tree")
I am able to look at the data returned by the call to knn using the code below:
> attr(k, "nn.dist")[1,]
[1] 1385.398 1687.901 1722.884 1846.694 1978.250 1998.157 2003.518 2004.494 2054.382 2059.128
> attr(k, "nn.index")[1,]
[1] 983 362 170 303 914 843 480 489 474 355
What I would like to do is modify the values that are in nn.dist based on the values that are in nn.index.
I know this probably doesn’t make sense, but for the sake of argument, how would I go about setting each value in nn.dist to nn.dist * nn.index/1000?
So attr(k, "nn.dist")[1,1] would go from 1385.398 to 1385.398*983/1000 (1361.846)
and
attr(k, "nn.dist")[1,2] would go from 1687.901 to 1687.901*362/1000 (611.02) etc.
I am able to do this one at a time with the following code:
attr(k, "nn.dist")[1,1] = attr(k, "nn.dist")[1,1]*attr(k, "nn.index")[1,1]/1000
But I need a way to do this to every element, without writing it every time…
The basic operators
*,+,/and-are vectorised and will work elementwise on an array.Therefore it is as easy as
If you only want to do this to the first row of
nn.dist, thenYou could reassign to the
nn.distattribute ofk, but I would suggest copying to ensure that you know that it is not the original output egor you could simply add a new attribute to the original