[英]MarkovChain package error in R when creating attribution model : Error! Rows of transition matrix do not some one
我正在按照本教程在 R 中創建用於歸因建模的馬爾可夫鏈。
但是,當我運行它時,我得到一個編譯錯誤,在這個頁面上提出了一個解決方案,但是它仍然給出相同的錯誤,我還嘗試了兩種不同的解決方法來克服編譯錯誤,但都導致運行時錯誤 output看起來不像教程中的那個。 解決方法記錄在底部。
對此的任何幫助將不勝感激。
library(dplyr)
library(reshape2)
library(ggplot2)
library(ggthemes)
library(ggrepel)
library(RColorBrewer)
library(ChannelAttribution)
library(markovchain)
##### simple example #####
# creating a data sample
df1 <- data.frame(path = c('c1 > c2 > c3', 'c1', 'c2 > c3'), conv = c(1, 0, 0), conv_null = c(0, 1, 1))
# calculating the model
mod1 <- markov_model(df1,
var_path = 'path',
var_conv = 'conv',
var_null = 'conv_null',
out_more = TRUE)
# extracting the results of attribution
df_res1 <- mod1$result
# extracting a transition matrix
df_trans1 <- mod1$transition_matrix
df_trans1 <- dcast(df_trans1, channel_from ~ channel_to, value.var = 'transition_probability')
### plotting the Markov graph ###
df_trans <- mod1$transition_matrix
# adding dummies in order to plot the graph
df_dummy <- data.frame(channel_from = c('(start)', '(conversion)', '(null)'),
channel_to = c('(start)', '(conversion)', '(null)'),
transition_probability = c(0, 1, 1))
df_trans <- rbind(df_trans, df_dummy)
# ordering channels
df_trans$channel_from <- factor(df_trans$channel_from,
levels = c('(start)', '(conversion)', '(null)', 'c1', 'c2', 'c3'))
df_trans$channel_to <- factor(df_trans$channel_to,
levels = c('(start)', '(conversion)', '(null)', 'c1', 'c2', 'c3'))
df_trans <- dcast(df_trans, channel_from ~ channel_to, value.var = 'transition_probability')
# creating the markovchain object
trans_matrix <- matrix(data = as.matrix(df_trans[, -1]),
nrow = nrow(df_trans[, -1]), ncol = ncol(df_trans[, -1]),
dimnames = list(c(as.character(df_trans[, 1])),
c(colnames(df_trans[, -1]))))
trans_matrix[is.na(trans_matrix)] <- 0
trans_matrix1 <- new("markovchain", transitionMatrix = trans_matrix)
# plotting the graph
plot(trans_matrix1, edge.arrow.size = 0.35)
錯誤發生在這一行
trans_matrix1 <- new("markovchain", transitionMatrix = trans_matrix)
Error:
Aggregation function missing: defaulting to length
Error in validObject(.Object) :
invalid class “markovchain” object: Error! Rows of transition matrix do not some one
編輯:
我嘗試了以下方法,都給出了運行時錯誤:
trans_matrix <- trans_matrix/rowSums(trans_matrix)
該消息包含一個英文錯誤:應該說“do not sum to one”而不是“do not some one”。 您使用的矩陣如下所示:
> trans_matrix
(start) (conversion) (null) NA
(start) 1 0 0 2
(conversion) 0 1 0 0
(null) 0 0 1 0
<NA> 0 1 2 2
要解決此問題,您可以使用每行除以其總和
trans_matrix <- trans_matrix/rowSums(trans_matrix)
之后就沒有錯誤了。 這是否是正確的矩陣,我不知道。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.