简体   繁体   English

如何使用 proxy::dist 应用自定义 function 以在 R 中创建距离矩阵

[英]How to apply a custom function with proxy::dist to create a distance matrix in R

I have defined a custom function and tested the function to make sure that it works but I am unable to apply it to a list in order to obtain a distance matrix.我已经定义了一个自定义 function 并测试了 function 以确保它有效,但我无法将它应用于列表以获得距离矩阵。

The code I have is:我的代码是:

library(Biostrings)
library(proxy)

#import the sequences using Biostrings
indf<-readAAStringSet("C:/Users/jamie/OneDrive/Documents/Junk/SAMPLEFASTA.fasta")

#Assign the names and sequences to different variables
seqAAname<-names(indf)
seqz<-paste(indf)

#Put just the sequences into a dataframe
indf2<-data.frame(seqz)

#Convert the sequences into a list
indf3<-as.list(indf2)

#Define a custom function to return the alignment score between two sequences (pairwise)
customalnfunc <- function(X, Y){
  pairwiseAlignment(X, Y,
                    substitutionMatrix = "BLOSUM45", gapOpening = 1, gapExtension = 3)
}

#Test the function but not as a function (This works fine)
testfreefunc<-  pairwiseAlignment(AAString("PEHQRSTVE"),AAString("PQHQRETVE"),
                    substitutionMatrix = "BLOSUM45", gapOpening = 1, gapExtension = 3)
print(testfreefunc@score)


#Test the function as a fucntion to make sure it works (This works fine)
testfuncout <- customalnfunc(AAString("PEHQRSTVE"),AAString("PQHQRETVE"))
print(testfuncout@score)

#Apply the custom function to all possible pairs using proxy::dist with the custom function (This does not work, it returns 0)
outalnmatrix <- proxy::dist(indf3, method = customalnfunc)
outalnmatrix

The SAMPLEFASTA.fasta file contains: SAMPLEFASTA.fasta 文件包含:

>SeqA
PEHQRSTVE
>SeqB
PQHQRETVE
>SeqC
RQHERSEVE

The desired output from outalnmatrix is:来自 outalnmatrix 的所需 output 是: 在此处输入图像描述

I have tried passing the input data to proxy::dist as a list and a matrix.我尝试将输入数据作为列表和矩阵传递给 proxy::dist。

How can I make this work?我怎样才能使这项工作?

You don't need to use the proxy package as proxy::dist is meant to icompare rows of matrix/dataframes against each other.您不需要使用proxy package,因为proxy::dist用于比较矩阵/数据帧的行。 Since you want to compare strings, you can use outer .既然你想比较字符串,你可以使用outer However, you need to tweak your customalnfunc function, so that it returns only a number ( scoreOnly = TRUE ).但是,您需要调整您的customalnfunc function,以便它仅返回一个数字 ( scoreOnly = TRUE )。

library(Biostrings)

seqz <- c("PEHQRSTVE", "PQHQRETVE", "RQHERSEVE")

customalnfunc <- function(X, Y){
  pairwiseAlignment(X, Y,
                    substitutionMatrix = "BLOSUM45",
                    gapOpening = 1,
                    gapExtension = 3,
                    scoreOnly = TRUE)
}

outer(seqz, seqz, customalnfunc)

#>
     [,1] [,2] [,3]
[1,]   58   50   33
[2,]   50   60   33
[3,]   33   33   57


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

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