【问题标题】:Combine variables into numeric vector and find distance between them将变量组合成数值向量并找出它们之间的距离
【发布时间】:2021-06-25 13:35:06
【问题描述】:

我有四个数值变量,我想将它们组合成两个向量,然后计算这些向量之间的距离。

df = data.frame(V1 = 1:10, 
                V2 = 11:20, 
                V3 = 21:30, 
                V4 = 31:40)

我可以这样创建向量:

df2 <- df %>% 
mutate(vector1 = mapply(c, V1, V2, SIMPLIFY = F),
       vector2 = mapply(c, V3, V4, SIMPLIFY = F))

但我无法将它们强制为数字,因此我无法计算它们之间的距离:

 # want to be able to do something like this
 df2 %>% 
 mutate(distance = sqrt(sum((vector1 - vector2) ^ 2)))

我尝试了各种组合:

distance_df$vector1 <- lapply(distance_df$vector1, as.numeric)
distance_df$vector1 <- as.numeric(as.character(distance_df$vector1))

我一定遗漏了一些很明显的东西,因为这似乎并不难。

【问题讨论】:

    标签: r vector dplyr


    【解决方案1】:

    这可能是一种选择吗?

    library(tidyverse)
    df = data.frame(V1 = 1:10, 
                    V2 = 11:20, 
                    V3 = 21:30, 
                    V4 = 31:40)
    
    df %>% 
      rowwise() %>% 
      mutate(distance = sqrt(sum((c(V1,V2) - c(V3,V4)) ^ 2)))
    

    【讨论】:

    • 太棒了,而且超级高效!谢谢!
    猜你喜欢
    • 2016-12-02
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    • 2015-06-05
    • 2020-09-03
    • 2018-08-07
    相关资源
    最近更新 更多