根据最小距离将点分配给组
Assign points to a group based on minimum distance
我正在尝试根据欧氏距离将点分配到分组中。例如,在下面的数据中,有三个点代表三个不同的组(One, Two, Three
,图中的非绿色点)。我想根据最小欧氏距离(即将 Scatter
更改为最接近的 One
Two
将剩余的点(Scatter
绿点)分配到一个分组中或 Three
点。
我试图在 kmeans
或其他聚类函数之外执行此操作,并且只是使用最小欧几里得距离,但欢迎并感谢您的建议。
set.seed(123)
Data <- data.frame(
x = c(c(3,5,8), runif(20, 1, 10)),
y = c(c(3,5,8), runif(20, 1, 10)),
Group = c(c("One", "Two", "Three"), rep("Scatter", 20))
)
ggplot(Data, aes(x, y, color = Group)) +
geom_point(size = 3) +
theme_bw()
像这样的事情怎么样:
bind_cols(
Data,
dist(Data %>% select(-Group)) %>% # Get x/y coordinates from Data
as.matrix() %>% # Convert to full matrix
as.data.frame() %>% # Convert to data.frame
select(1:3) %>% # We're only interested in dist to 1,2,3
rowid_to_column("pt") %>%
gather(k, v, -pt) %>%
group_by(pt) %>%
summarise(k = k[which.min(v)])) %>% # Select label with min dist
mutate(Group = factor(Group, levels = unique(Data$Group))) %>%
ggplot(aes(x, y, colour = k, shape = Group)) +
geom_point(size = 3)
说明:我们使用 One
、Two
、Three
和所有 Scatter
点之间的 dist
计算所有成对欧几里得距离。然后我们根据每个 Scatter
点到 One
(k = 1
), Two
(k = 2
), Three
(k = 3
).
请注意,(9.6, 3.1) 处的 Scatter
点确实正确 "classified" 属于 Two
(k = 2
);您可以通过在 ggplot
情节链中添加 coord_fixed()
来确认这一点。
我正在尝试根据欧氏距离将点分配到分组中。例如,在下面的数据中,有三个点代表三个不同的组(One, Two, Three
,图中的非绿色点)。我想根据最小欧氏距离(即将 Scatter
更改为最接近的 One
Two
将剩余的点(Scatter
绿点)分配到一个分组中或 Three
点。
我试图在 kmeans
或其他聚类函数之外执行此操作,并且只是使用最小欧几里得距离,但欢迎并感谢您的建议。
set.seed(123)
Data <- data.frame(
x = c(c(3,5,8), runif(20, 1, 10)),
y = c(c(3,5,8), runif(20, 1, 10)),
Group = c(c("One", "Two", "Three"), rep("Scatter", 20))
)
ggplot(Data, aes(x, y, color = Group)) +
geom_point(size = 3) +
theme_bw()
像这样的事情怎么样:
bind_cols(
Data,
dist(Data %>% select(-Group)) %>% # Get x/y coordinates from Data
as.matrix() %>% # Convert to full matrix
as.data.frame() %>% # Convert to data.frame
select(1:3) %>% # We're only interested in dist to 1,2,3
rowid_to_column("pt") %>%
gather(k, v, -pt) %>%
group_by(pt) %>%
summarise(k = k[which.min(v)])) %>% # Select label with min dist
mutate(Group = factor(Group, levels = unique(Data$Group))) %>%
ggplot(aes(x, y, colour = k, shape = Group)) +
geom_point(size = 3)
说明:我们使用 One
、Two
、Three
和所有 Scatter
点之间的 dist
计算所有成对欧几里得距离。然后我们根据每个 Scatter
点到 One
(k = 1
), Two
(k = 2
), Three
(k = 3
).
请注意,(9.6, 3.1) 处的 Scatter
点确实正确 "classified" 属于 Two
(k = 2
);您可以通过在 ggplot
情节链中添加 coord_fixed()
来确认这一点。