gpt4 book ai didi

r - 加快独特观测值的成对计数

转载 作者:行者123 更新时间:2023-12-04 12:29:30 26 4
gpt4 key购买 nike

我有一个对象向量 ( object ) 以及观察对象的相应时间框架向量 ( tframe )。对于每对唯一的对象,我想计算观察到两个对象的时间范围的数量。

我可以使用 for() 编写代码循环,但随着唯一对象数量的增加,它需要很长时间才能运行。如何更改代码以加快运行时间?

下面是一个包含 4 个独特对象的示例(实际上我有大约 300 个)。例如,对象 ac都在时间范围内观察到 12 ,所以他们得到 2 的计数.对象 bd从未在同一时间范围内观察到,因此它们的计数为 0 .

object <- c("a", "a", "a", "b", "b", "c", "c", "c", "c", "d")
tframe <- c(1, 1, 2, 2, 3, 1, 2, 2, 3, 1)

uo <- unique(object)
n <- length(uo)

mpairs <- matrix(NA, nrow=n*(n-1)/2, ncol=3, dimnames=list(NULL,
c("obj1", "obj2", "sametf")))

row <- 0
for(i in 1:(n-1)) {
for(j in (i+1):n) {
row <- row+1
mpairs[row, "obj1"] <- uo[i]
mpairs[row, "obj2"] <- uo[j]
# no. of time frames in which both objects in a pair were observed
intwin <- intersect(tframe[object==uo[i]], tframe[object==uo[j]])
mpairs[row, "sametf"] <- length(intwin)
}}

data.frame(object, tframe)
object tframe
1 a 1
2 a 1
3 a 2
4 b 2
5 b 3
6 c 1
7 c 2
8 c 2
9 c 3
10 d 1

mpairs
obj1 obj2 sametf
[1,] "a" "b" "1"
[2,] "a" "c" "2"
[3,] "a" "d" "1"
[4,] "b" "c" "2"
[5,] "b" "d" "0"
[6,] "c" "d" "1"

最佳答案

您可以使用 crossproduct得到协议(protocol)的计数。然后你可以 reshape
数据,如果需要的话。

例子

object <- c("a", "a", "a", "b", "b", "c", "c", "c", "c", "d")
tframe <- c(1, 1, 2, 2, 3, 1, 2, 2, 3, 1)

# This will give you the counts
# Use code from Jean's comment
tab <- tcrossprod(table(object, tframe)>0)

# Reshape the data
tab[lower.tri(tab, TRUE)] <- NA
reshape2::melt(tab, na.rm=TRUE)

关于r - 加快独特观测值的成对计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37689287/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com