首页 > 解决方案 > 计算并返回 R 中矩阵 A 和 B 之间的单个距离值

问题描述

我看过关于矩阵 A 和 B 之间距离(​​主要是欧几里得)的类似帖子。但是它们返回每个匹配观察值(行)之间距离的矩阵。

现在我有这个问题,假设我有一个药物治疗列表,每个治疗都是一个包含 N 行 x 9 列矩阵的列表。所以每个治疗列表都有不同的行(实验对象),但所有的列(变量)都是相同的。

我想根据同一实验对象根据测量变量对治疗的反应来比较治疗的相似程度。所以我来看看我是否可以计算每个治疗矩阵之间的距离并返回一个值,然后我可以在一个矩阵中包含所有治疗之间的比较。最后,我可以通过层次聚类可视化热图中的治疗关系。

 #take 2 treatments as an example:
 set.seed(123)
 Treatment1 <- data.frame(x=sample(1:10000,3), 
               y=sample(1:10000,3), 
               z=sample(1:10000,3))
 Treatment2 <- data.frame(x=sample(1:100,3), 
               y=sample(1:100,3), 
               z=sample(1:1000,3))

 #lets say I have 10 treatments/drugs aka length(Drugs)= 10
 Drugs <- list(Treatment1,Treatment2,...Treatment10 )

 #load an empty matrix to record all distances
 distance <- matrix(1, nrow = length(Drugs), ncol = length(Drugs))

 #now I want to construct the matrix of all the distance measurements:

 for (i in 1:(length(Drugs) - 1)){
  for (j in (i+1):length(Drugs)){
  # Match by ID, lets assume the 1st column is the ID
  total <- inner_join(Drugs[[i]], Drugs[[j]], by = c("ID"))
  # Calculate distance and store 
  distance <- #some sort of dist function(total[,drugi], total[,drugj])

  # Store in correct location on matrix
  distance_values[i,j] <- distance 
  distance_values[j,i] <- distance 

  plot(hclust(distance))

所以我被困在#some sort of dist function,对我来说所有的 distmap,pdist 函数返回两个矩阵之间的行观察之间的矩阵,因此我无法将矩阵加载到我的空矩阵的单个位置。我需要任何给定矩阵之间的单个数字。我说得有道理吗?我可以用什么函数来计算这样的距离?

标签: rmatrixdistance

解决方案


推荐阅读