Reputation: 31
So I understand that mapply will step through an array (or series of arrays) in element order – I was wondering if there was a way to STOP it from doing this on some of the arguments…. Let me explain further
I have a set of data points, with X and Y coordinates… X1 X2 … Xn and Y1 Y2 … Yn I have a set of centres, with X and Y coordinates… Cx1, Cx2, Cx3 and Cy1, Cy2, Cy3 For each data point I want to find out which “centre” it is closest to… (cluster matching) apologies for using the english version of centre
I’ve got a working function that takes an X coord and a Y coord and the centres and works out the distance and the nearest centre
assignCentre <- function (x1, y1, xcentres, ycentres) {
centredists <- mapply(pointDistance, x1, y1, xcentres, ycentres)
nearcentre <- which(centredists == min(centredists))[1]
return(list(nearcentre, centredists[nearcentre]))
}
pointDistance <- function (x1, y1, x2, y2) {
xdist <- (x2 - x1) ^ 2
ydist <- (y2 - y1) ^ 2
return(sqrt(xdist + ydist))
}
Here’s the issue, if I try the following: mapply(assignCentre, xcoords, ycoords, xcentres, ycentres) it fails because basically it runs
assignCentre(x1, y1, Cx1, Cy1)
assignCentre(x2, y2, Cx2, Cy2)
assignCentre(x3, y3, Cx3, Cy3)
what I want it to run is:
assignCentre(x1, y1, (Cx1, Cx2, Cx3), (Cy1, Cy2, Cy3))
assignCentre(x2, y2, (Cx1, Cx2, Cx3), (Cy1, Cy2, Cy3))
assignCentre(x3, y3, (Cx1, Cx2, Cx3), (Cy1, Cy2, Cy3))
...
...
assignCentre(xn, yn, (Cx1, Cx2, Cx3), (Cy1, Cy2, Cy3))
any ideas how I can get mapply to strip apart xcoords and ycoords but leave the centre coords alone? – or should I just use a for loop?
Upvotes: 3
Views: 94
Reputation: 206232
If you don't want to iterate over parameters, stick them in the MoreArgs=
parameter
mapply(assignCentre, x, y,
MoreArgs=list(xcentres=xcentres, ycentres=ycentres))
Upvotes: 4