R 我有一个mapply函数可以工作-如何将其转换为mlply?

R 我有一个mapply函数可以工作-如何将其转换为mlply?,r,algorithm,progress-bar,plyr,mapply,R,Algorithm,Progress Bar,Plyr,Mapply,我编写了以下R代码,将最近的邮政编码分配给一组北距/东距坐标: # Set of northing / easting coordinates that I need to assign a postcode to x1 <- c(1,2,4,6,7) y1 <- c(5,2,4,7,8) # Postcode with northing / easting coordinates postcode <- c("Postcode A", "Postcode B", "Post

我编写了以下R代码,将最近的邮政编码分配给一组北距/东距坐标:

# Set of northing / easting coordinates that I need to assign a postcode to
x1 <- c(1,2,4,6,7)
y1 <- c(5,2,4,7,8)

# Postcode with northing / easting coordinates
postcode <- c("Postcode A", "Postcode B", "Postcode C", "Postcode D")
x2 <- c(5,3,4,2)
y2 <- c(8,1,2,4)

# Function that attributes closest postcode to (x1, y1) coordinates
algo <- function(x, y)
{
        dist <- which.min(sqrt(((x2 - x)^2) + ((y2 - y)^2)))
}

# mapply to run the function, and find the closest coordinates
postcode[mapply(algo, x1, y1, SIMPLIFY = T)]
[1] "Postcode D" "Postcode B" "Postcode C" "Postcode A" "Postcode A"
我做错了什么?如能为mlply(或其他m*ply函数)提供正确的R代码,并解释上述内容不正确的原因,将不胜感激


非常感谢您的时间和关注。

我至少发现了两个问题

首先,数据框中的列名称与函数中的参数名称不匹配。以下代码在没有警告的情况下工作

mlply(cbind(x= x1, y =y1), .fun = algo, .progress = "tk")
第二个,mlply返回一个列表,其中包含无法用于对邮政编码向量进行子集的元素:

mlply(.data = cbind(x = x1, y = y1), .fun = algo, .progress = "tk")
$
1
[1] 四,

$
2
[1] 二,

$
3
[1] 三,

$
4
[1] 一,

$
5
[1] 一,

属性(,“拆分类型”) [1] “数组” 属性(,“拆分标签”) xy 1 1 5 2 2 2 3 4 4 4 6 7 578

要解决这个问题,我建议:

postcode[unlist(mlply(.data = cbind(x = x1, y = y1), 
    .fun = algo, .progress = "tk"))[1:length(x1)]]

<强>最后< /强>,如果你尝试寻找最小距离,你可以直接考虑寻找最小平方距离(你避免计算平方根一百万次,这应该会改善时间)。

postcode[unlist(mlply(.data = cbind(x = x1, y = y1), 
    .fun = algo, .progress = "tk"))[1:length(x1)]]