x <- runif(100, -10, 10)
y <- runif(100, -10, 10)
closest_points <- data.frame(x1 = numeric(), y1 = numeric(), x2 = numeric(), y2 = numeric())
for (i in 1:length(x)) {
current_point <- c(x[i], y[i])
distances <- sqrt((x - x[i])^2 + (y - y[i])^2) # 计算当前点与其他点的距离
nearest_point_index <- which.min(distances) # 找出最近点的索引
nearest_point <- c(x[nearest_point_index], y[nearest_point_index])
closest_points <- rbind(closest_points, c(current_point, nearest_point))
}
print(closest_points)
为什么我算出来是当前点本身
【以下回答由 GPT 生成】
问题的关键在于使用c()
函数将当前点和最近点的坐标添加到closest_points
数据框中的代码。c()
函数在这里将两个坐标向量合并为一个单一的向量,这是导致最近点的坐标是当前点本身的原因。
为了解决这个问题,我们可以使用data.frame()
函数将两个坐标向量合并为一个数据框。下面是修复后的代码:
for (i in 1:length(x)) {
current_point <- data.frame(x1 = x[i], y1 = y[i])
distances <- sqrt((x - x[i])^2 + (y - y[i])^2)
nearest_point_index <- which.min(distances)
nearest_point <- data.frame(x2 = x[nearest_point_index], y2 = y[nearest_point_index])
closest_points <- rbind(closest_points, c(current_point, nearest_point))
}
修复后的代码将每个坐标作为单独的数据框合并到closest_points
中,保留了原始的数据框结构,并正确存储了最近点的坐标。
请注意,上述修复后的代码可能会导致运行时间较长,因为在每个循环迭代中都要合并数据框。如果数据集很大,可以考虑先创建包含正确列名的预定义大小的空数据框,然后在每个迭代中将数据存储到预定义的行中,以避免重复的数据框合并操作。
如果以上答案仍然有问题,请说明具体问题所在,我会尽力帮助解决。
【相关推荐】