I have a distance function which takes in 2 (numeric) vectors and calculates the distance between them.
For a given dataframe (mtcars_raw
) in the example below and a fixed input vector (test_vec
) I would like to calculate the pairwise distances (i.e. apply the distance function) to each column and test_vec
and return the vector of distances. The length of the vector should be the number of columns.
Please see the reproducible example:
library(datasets)
# The raw dataframe containing only numeric columns
mtcars_raw <- datasets::mtcars
# The distance function between 2 vectors (of the same length typically)
eucl_dist <- function(x, y){
return(sqrt(sum((x-y)^2)))
}
# An example of a numeric vector to check the distance against each column
test_vec <- rnorm(n = dim(mtcars_raw)[1], mean = 12, sd = 2)
# Manually for the first column, we would have:
dist_1 <- eucl_dist(x = test_vec, mtcars_raw[, 1])
dist_1
#> [1] 58.71256
# Manually for the second column, we would have:
dist_2 <- eucl_dist(x = test_vec, mtcars_raw[, 1])
dist_2
#> [1] 58.71256
# Would like dist_comb returned for all columns without having to manually do
# the combining
dist_comb <- c(dist_1, dist_2)
dist_comb
#> [1] 58.71256 58.71256
Could anyone please show the purrr (tidyverse)
code to return vector on each column of mtcars_raw against test_vec?