使用单个人的时间序列数据,我可以计算一阶概率转移矩阵,即库(markovchain(,并计算其密度,即库
此代码有效:
ds = matrix(c(1,1,2,1,2,4,1,3,6,1,4,8),ncol=3,byrow=TRUE) #create person period data for a single person
colnames(ds) = c("Id", "Time", "Evt")
ds = as.data.frame(ds)
mc = markovchainFit(ds$Evt, name = "mc")$estimate #calculate markovchain
am = mc@transitionMatrix #remove slot from S4 object
em = network(am, matrix.type="adjacency", directed=TRUE, Weighted = TRUE, loops = FALSE) #make network object
gden(em)#calculate density of network, etc
但我很难使用tapply使其适用于具有多个ID的数据。这段代码在第4行之后就不起作用了,但这就是我脑海中的解决方案:
ds2 = matrix(c(1,1,2,1,2,4,1,3,6,1,4,8,2,1,3,2,2,5,2,3,7,2,4,9),ncol=3,byrow=TRUE) #create person period data for two people
colnames(ds2) = c("Id", "Time", "Evt")
ds2 = as.data.frame(ds2)
mc2 = tapply(ds2$Evt, ds2$Id, markovchainFit) #it works to here and I am STUCK for days *see below
am2 = mc@transitionMatrix, #can't figure how to integrate these steps from above
em2 = network(am, matrix.type="adjacency", directed=TRUE, Weighted = TRUE, loops = FALSE)
gden(em2)
*对于列表中的每个人,我都无法计算:
- 如何命名马尔可夫链S4对象
- 如何从S4对象中删除转换矩阵槽
- 如何在markovchainFit之后传递附加函数
有人对如何通过ID向量循环我对一个人的分析有什么建议吗?非常感谢。
下面这样的怎么样。在下面的代码中,我制作了一个函数,它完成所有的临时工作,并在适当的对象上返回gden()
的结果。
ds2 = matrix(c(1,1,2,1,2,4,1,3,6,1,4,8,2,1,3,2,2,5,2,3,7,2,4,9),ncol=3,byrow=TRUE) #create person period data for two people
colnames(ds2) = c("Id", "Time", "Evt")
ds2 = as.data.frame(ds2)
mcfun <- function(x){
mc <- markovchainFit(x, name="mc")$estimate
am <- mc@transitionMatrix
em <- network(am, matrix.type="adjacency", directed=TRUE, Weighted = TRUE, loops = FALSE) #make network object
gden(em)#calculate density of network, etc
}
tapply(ds2$Evt, ds2$Id, mcfun)
# 1 2
# 0.25 0.25