简体   繁体   English

如何在R中反复运行欧几里德距离

[英]How to run euclidean distance over and over in R

If I have a file in R like so 如果我在R中有一个文件就像这样

dput(filename)
structure(list(word = structure(c(2L, 1L), .Label = c("frq", 
"ocr_avg"), class = "factor"), abeja = c(98, 24), abeja.1 = c(26.666, 
3), abrigo = c(53.333, 6), abrigo.1 = c(50, 1), abrigo.2 = c(83.809, 
21), abrigo.3 = c(31.666, 6)), .Names = c("word", "abeja", "abeja.1", 
"abrigo", "abrigo.1", "abrigo.2", "abrigo.3"), row.names = c(NA, 
-2L), class = "data.frame")

#      word abeja abeja.1 abrigo abrigo.1 abrigo.2 abrigo.3
# 1 ocr_avg    98  26.666 53.333       50   83.809   31.666
# 2     frq    24   3.000  6.000        1   21.000    6.000

And I want to calculate the euclidean distance between pairs with the same name, so for example between (abeja & abeja.1), then between (abrigo & abrigo.1) and (abrigo & abrigo.2) and (abrigo & abrigo.3). 我想计算具有相同名称的对之间的欧几里德距离,例如(abeja和abeja.1)之间,然后是(abrigo和abrigo.1)和(abrigo&abrigo.2)和(abrigo&abrigo。 3)。 but also between (abrigo.1 & abrigo.2) and (abrigo.2 & abrigo.3). 但也在(abrigo.1和abrigo.2)和(abrigo.2&abrigo.3)之间。

Is there a way to automate this so that I don't have to go through every pair and do it myself (it's a pretty big file) in R? 有没有办法自动化这个,这样我就不必经历每一对并自己做(在R中它是一个非常大的文件)?

The way I'm doing this on my own is like this: 我自己这样做的方式是这样的:

x <- filename$abeja
y <- filename$abeja.1 
dist(rbind(x,y))
mystring <- names(filename)

library(stringr)

# take the common patterns
strUniq <- unique(ifelse(str_detect(mystring, '\\.'), 
                         str_sub(mystring, 1, str_locate(mystring, '\\.')[,1] -1), 
                         mystring))
strUniq

# [1] "word"   "abeja"  "abrigo"

library(dplyr)
outp <- lapply(strUniq, function(x) select(filename, starts_with(x)))
outp

# [[1]]
#      word
# 1 ocr_avg
# 2     frq
#
# [[2]]
#   abeja abeja.1
# 1    98  26.666
# 2    24   3.000
#
# [[3]]
#   abrigo abrigo.1 abrigo.2 abrigo.3
# 1 53.333       50   83.809   31.666
# 2  6.000        1   21.000    6.000

lapply(outp, function(x) dist(t(x)))

# [[1]]
# dist(0)
#
# [[2]]
#            abeja
# abeja.1 74.36087
#
# [[3]]
#             abrigo  abrigo.1  abrigo.2
# abrigo.1  6.009067                    
# abrigo.2 33.967434 39.281656          
# abrigo.3 21.667000 19.003567 54.257649
#
# Warning message:
# In dist(t(x)) : NAs introduced by coercion

The warning is due to "word" which does not contain numbers. 警告是由于“word”不包含数字。 You can remove it first to avoid the warning. 您可以先将其删除以避免警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM