计算多列数据框 r 的平均欧氏距离

Calculate mean euclidean distance of multiple columns dataframe r

我有一个如下所示的数据框:

df <- data.frame(text = c("text1", "text2", "text3"),
             a = c(1,2,3),
             b = c(2,4,6),
             c = c(3,6,9))
df

对于每一行,我想使用以下方法计算 a、b 和 c 列中的值之间的距离的平均值:

mean(dist())

我想将结果存储在名为 "score" 的列中。结果应如下所示:

df <- data.frame(text = c("text1", "text2", "text3"),
             a = c(1,2,3),
             b = c(2,4,6),
             c = c(3,6,9),
             score = c(mean(dist(c(1,2,3))),
                       mean(dist(c(2,4,6))),
                       mean(dist(c(3,6,9)))))
df

搜索 Whosebug 我只能找到将一行转换为向量的示例。我也尝试了很多自己的方法,但每次都卡住了。这可能是由于缺乏基本的 R 知识。请帮我解决这个问题。非常感谢您的帮助!

不知道对你有没有帮助:

df <- data.frame(text = c("text1", "text2", "text3"),
             a = c(1,2,3),
             b = c(2,4,6),
             c = c(3,6,9))
score= c(mean(dist(c(1,2,3))),
      mean(dist(c(2,4,6))),
      mean(dist(c(3,6,9))))
df = cbind(df,score)

结果是

df
text a b c    score
1 text1 1 2 3 1.333333
2 text2 2 4 6 2.666667
3 text3 3 6 9 4.000000

A+

试试这个简单的解决方案。

第 1 步:创建一个函数 f 计算所有距离的平均值

f<-function(x)
{
  return(mean(dist(x)))
}

第 2 步: 按每一行应用函数并将输出插入 score

df$score<-apply(df[,-1],1,f)

你的输出

    df
   text a b c    score
1 text1 1 2 3 1.333333
2 text2 2 4 6 2.666667
3 text3 3 6 9 4.000000

@JuanAntonioRoldánDiaz 是正确答案。

df$score <- apply(df[,2:4], 1, function(x) mean(dist(x)))