r - 如何使用 apply 而不是 for 循环来实现 stringMatch 函数?

标签 r for-loop string-matching apply

我试图计算一长串序列之间成对差异的数量,并将其放回矩阵形式。这是我想做的一个玩具示例。

library(MiscPsycho)
b <- c("-BC", "ACB", "---") # Toy example of sequences
workb <- expand.grid(b,b)
new <- c(1:9)

# Need to get rid of this for loop somehow
for (i in 1:9) {
new[i] <- stringMatch(workb[i,1], workb[i,2], normalize="NO")
}

workb <- cbind(workb, new)
newmat <- reShape(workb$new, id=workb$Var1, colvar=workb$Var2)

a <- c("Subject1", "Subject2", "Subject3") #Relating it back to the subject ID
colnames(newmat) <- a
rownames(newmat) <- a
newmat

我不太熟悉使用 apply 函数,但我想用它来替换 for 循环,考虑到我有大量序列,for 循环可能会变慢。 (stringMatch 函数来自 MiscPsycho)。请告诉我如何提高效率!

非常感谢!

最佳答案

为了获得这些“成对距离”,我会这样做:

  Vm <- Vectorize(stringMatch)
  nex <- outer(b,b, FUN=Vm, normalize = "NO")
 nex
     [,1] [,2] [,3]
[1,]    0    3    2
[2,]    3    0    3
[3,]    2    3    0

关于r - 如何使用 apply 而不是 for 循环来实现 stringMatch 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11107097/

相关文章:

string - R中的快速部分字符串匹配

python - 为什么使用正则表达式 finditer() 而不是 findall()

r - 将 %B.%Y 转换为 R 中的日期返回 NA

javascript - 带嵌套 IF 语句的 FOR LOOP

r - R 中的函数、For 循环和条件

python - 如何阻止值返回 'None' ?

python - 搜索允许在字符串的任何位置出现一个不匹配的字符串

java - 将 jar 文件下载到 R 包的 inst/java 目录中

r - 如何比较 R 中多个数据集中同一位置的每个值

r - 将列传递给 dplyr 中的 kableExtra 参数