Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 查找向量中哪些元素的编辑距离为1且长度相同?_R_For Loop - Fatal编程技术网

R 查找向量中哪些元素的编辑距离为1且长度相同?

R 查找向量中哪些元素的编辑距离为1且长度相同?,r,for-loop,R,For Loop,我有一个dataframe,下面是一个.csv格式的示例,它有一个单词列表(Word)、这些单词中的声音数量(NumSounds)以及每个单词中声音的转录(发音)。我一直在尝试创建一个文件,显示列表中每个单词的最小对数。这意味着,对于每个单词,我需要知道列表中哪些其他单词与该单词的编辑距离为1,同时也具有相同的发音数。我一直在做的是R。我的实验室伙伴编写的循环如下所示: library(stringdist) words = vector(mode="character", length=nro

我有一个dataframe,下面是一个.csv格式的示例,它有一个单词列表(Word)、这些单词中的声音数量(NumSounds)以及每个单词中声音的转录(发音)。我一直在尝试创建一个文件,显示列表中每个单词的最小对数。这意味着,对于每个单词,我需要知道列表中哪些其他单词与该单词的编辑距离为1,同时也具有相同的发音数。我一直在做的是R。我的实验室伙伴编写的循环如下所示:

library(stringdist)
words = vector(mode="character", length=nrow(df))
pairs = vector(mode="character", length=nrow(df))

pb = txtProgressBar(min=0, max=nrow(df), style=3)
for(i in 1:nrow(df)) {
  word = df$Pronunciation[i]
  nphones = df$NumSounds[i]
  potential_minimal_pairs = as.list(df$Pronunciation[df$Word != word & df$NumSounds == nphones])
  distances = stringdist(word, potential_minimal_pairs, method="lv")
  minimal_pairs = potential_minimal_pairs[distances == 1]
  word = unique(df$Word[datf$Pronunciation == word])[1]
  words = append(words, word)
  words[i] = word
  minimal_pairs = sapply(pairs, function(x) unique(df$Word[datf$Pronunciation == x])[1])
  pairs[i] = paste(minimal_pairs, ", ")
  setTxtProgressBar(pb, i)
}

myminimalpairs = data.frame(word=words, pairs=pairs)
head(myminimalpairs, 10)
单词、NumSounds、发音
阿比,3号和比号
遵守,4,b#d
中止,5,^b>rt
国外,5,^br>d
突然,6,^br^pt
缺勤,6岁及以上
缺席,6岁及以上
吸收,6,^bz>rb
吸收,7,^bz>rbd
摘要、第8章、bstr和kt
被虐待,6,^byuzd
深渊,4,^bIs
口音、7和K音
接受、7和k接受
已访问、6和k测试
雅阁,5,^k>路
指控,5,^kyuz
实现,4,^Civ
已实现,5,^Civd

aching,4,ekIN
一个选项是使用
stringdistmatrix()
创建一个等于1的距离矩阵,并使用
outer()
创建第二个相等数值的矩阵。然后可以使用数组索引返回符合条件的词对(仅使用较低的三角形以避免重复)

库(stringdist)
m1
library(stringdist)

m1 <- as.matrix(stringdistmatrix(df$Word, method = "lv", useNames = TRUE)) == 1
m2 <- outer(df$NumSounds, df$NumSounds, `==`)
idx <- which(m1 & m2 & lower.tri(m1), arr.ind = TRUE)
data.frame(word1 = df$Word[idx[,1]], word2 = df$Word[idx[,2]], stringsAsFactors = FALSE)

    word1   word2
1 accepts accents