【发布时间】:2017-10-10 23:03:14
【问题描述】:
我有一个距离函数,它接受 2 个(数字)向量并计算它们之间的距离。
对于下面示例中的给定数据框 (mtcars_raw) 和固定输入向量 (test_vec),我想计算每列和 test_vec 的成对距离(即应用距离函数)并返回距离向量。向量的长度应该是列数。
请看可重现的例子:
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
任何人都可以显示purrr (tidyverse) 代码以在 mtcars_raw 的每一列上针对 test_vec 返回向量吗?
【问题讨论】: