【问题标题】:Calculate mean euclidean distance of multiple columns dataframe r计算多列数据帧r的平均欧几里得距离
【发布时间】:2018-11-02 10:29:35
【问题描述】:

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

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

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

【问题讨论】:

  • df$score
  • df$score = sapply(df[,2:4], function(x) mean(dist(x)))
  • @JuanAntonioRoldánDíaz 回答有效,谢谢!我将其作为单独的答案发布以解决我的问题。不过2天内不能接受..

标签: r dataframe vector euclidean-distance


【解决方案1】:

我不知道这是否对你有帮助:

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+

【讨论】:

    【解决方案2】:

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

    第 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
    

    【讨论】:

    • 这不会返回与示例中显示的相同的分数值。
    • 对不起,代码是正确的,但不是复制粘贴到 SO。如您所见,我的答案与 JuanAntonioRoldanDianz 的逻辑相同,但在更扩展的版本中逐步解释。答案已更新。
    【解决方案3】:

    @JuanAntonioRoldánDíaz 发布了正确答案。

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

    【讨论】:

      猜你喜欢
      • 2013-04-07
      • 2021-01-31
      • 1970-01-01
      • 2023-03-03
      • 2020-02-21
      • 1970-01-01
      • 2021-01-28
      • 1970-01-01
      • 2021-03-30
      相关资源
      最近更新 更多