簡體   English   中英

計算多列數據框的平均歐式距離

[英]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())

我想將結果存儲在名為“分數”的列中。 結果應如下所示:

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

搜索Stackoverflow我只能找到將一行轉換為向量的示例。 我也嘗試了很多自己的方法,但是每次遇到困難時,我都會嘗試。 這可能是由於缺乏基礎R知識。 請幫我解決這個問題。 我非常感謝您的幫助!

試試這個簡單的解決方案。

第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ánDíaz發布了正確答案。

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

我不知道這是否對您有幫助:

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 +

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM