library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr 1.1.1 ✔ readr 2.1.4
✔ forcats 1.0.0 ✔ stringr 1.5.0
✔ ggplot2 3.4.2 ✔ tibble 3.2.1
✔ lubridate 1.9.2 ✔ tidyr 1.3.0
✔ purrr 1.0.1
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag() masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(palmerpenguins)
<- \(x, y, p){
knn_distance sum(abs(x-y)^p))^(1/p)
(
}
<- c(40, 19, 185, 3345)
new_penguin <- penguins %>% drop_na()
penguins_df <- penguins_df[,c(3:6)]
penguins_mat $manhattan <- penguins_mat %>%
penguins_dfapply(1, knn_distance, y = new_penguin, p = 1)
$euclidean <- penguins_mat %>%
penguins_dfapply(1, knn_distance, y = new_penguin, p = 2)
$m5 <- penguins_mat %>%
penguins_dfapply(1, knn_distance, y = new_penguin, p = 5)
%>% arrange(manhattan) %>%
penguins_df select(species, manhattan) %>% head(8)
# A tibble: 8 × 2
species manhattan
<fct> <dbl>
1 Chinstrap 11.2
2 Chinstrap 11.8
3 Adelie 14.9
4 Adelie 15.3
5 Adelie 22.3
6 Adelie 25.5
7 Adelie 27.2
8 Adelie 27.6
%>% arrange(euclidean) %>%
penguins_df select(species, manhattan) %>% head(8)
# A tibble: 8 × 2
species manhattan
<fct> <dbl>
1 Chinstrap 11.2
2 Chinstrap 11.8
3 Adelie 15.3
4 Adelie 14.9
5 Adelie 22.3
6 Adelie 25.5
7 Adelie 27.6
8 Adelie 27.2
%>% arrange(m5) %>%
penguins_df select(species, manhattan) %>% head(8)
# A tibble: 8 × 2
species manhattan
<fct> <dbl>
1 Chinstrap 11.2
2 Chinstrap 11.8
3 Adelie 15.3
4 Adelie 14.9
5 Adelie 22.3
6 Adelie 25.5
7 Adelie 27.6
8 Adelie 27.2