【发布时间】:2018-09-21 16:11:49
【问题描述】:
我有一个矩阵,我想确定每个字符在所有成对之间出现在同一位置的次数。
下面是我正在做的一个示例,但是我的矩阵有 10,000 行,并且花费的时间太长。
# This code will generate a dataframe with one row for each pair and columns that
# count the number of position match each letter have
my_letters <- c("A", "B", "C", "D")
size_vector <- 175
n_vectors <- 10
indexes_vectors <- seq_len(n_vectors)
mtx <- sapply(indexes_vectors,
function(i) sample(my_letters, n_vectors, replace = TRUE))
rownames(mtx) <- indexes_vectors
df <- as.data.frame(t(combn(indexes_vectors, m = 2)))
colnames(df) <- c("index_1", "index_2")
for(l in my_letters){
cat(l, "\n")
df[,l] <- apply(df[,1:2], 1,
function(ids) {
sum(mtx[ids[1],] == mtx[ids[2],] &
mtx[ids[1],] == l, na.rm = TRUE)
})
}
【问题讨论】:
-
我可能不明白到底发生了什么。您的输出
df包含列index_1、index_2和四个字母。所以在第一行,index_1 = 1和index_2 = 2。然后,您想知道这些字母在mtx[2, 1]和mtx[1, 2]上出现了多少次?但是每个索引对只有两个可能的字母,而您的输出df通常不止这些。你也错过了所有[x,x]职位,虽然我不知道这是不是故意的。 -
对于每个字母(“A”、“B”、“C”和“D”)我想知道它在@中的相同位置出现了多少次987654332@ 和
mtx[2, ]不在mtx[2, 1]和mtx[1,2]中。我故意错过了[x,x]。 -
简化您的代码以单独使用combn;并将我的改为使用 combn 而不是 CJ;使用不同的输入参数(在 # 字母等方面)运行,效果更好:chat.stackoverflow.com/transcript/message/42063793#42063793
-
非常感谢,我进行了更改,您的代码运行得更快了。
标签: r hamming-distance stringdist