R 从表中计算概率矩阵

R 从表中计算概率矩阵,r,matrix,R,Matrix,我有一个data.frame,如下所示: data <- read.table(text = 'Select.Actions,Current.State,Next.State Hire new staff,Out of Benchmark,Withinbenchmark Hire new staff,Out of Benchmark,Withinbenchmark Discuss with Customer,Withinbenchmark,Withinbenchmark Discuss w

我有一个data.frame,如下所示:

data <- read.table(text = 'Select.Actions,Current.State,Next.State
Hire new staff,Out of Benchmark,Withinbenchmark
Hire new staff,Out of Benchmark,Withinbenchmark
Discuss with Customer,Withinbenchmark,Withinbenchmark
Discuss with Customer,Withinbenchmark,Withinbenchmark
Discuss with Customer,Out of Benchmark,Out of Benchmark
Fire new staff,Out of Benchmark,Withinbenchmark
Discuss with Customer,Withinbenchmark,Withinbenchmark
Discuss with Customer,Out of Benchmark,Withinbenchmark
Fire new staff, Out of Benchmark,Withinbenchmar', 
                   header = TRUE, sep =",", stringsAsFactors = FALSE)

数据如果你在shriny之外构建函数,那么调试起来就容易多了,然后让它们交互。我也在shriny之外编写了它,但它不起作用,我以shriny的格式发布了我的问题,告诉程序员们整个故事。主要问题是TPM()的逻辑我认为您还不了解过渡矩阵方法可能适用的问题。您需要有一组状态,完全覆盖起点和终点的可能性。您需要有一个2列数据框,其中每列中的值都是该可能状态范围的子集。也许您需要说明如何从所提供的少量数据构建矩阵的概念。您可以构建三个独立的转换矩阵,每个“Select.Action”对应一个,但这似乎不是所要求的。您的意思是我必须创建3个数据帧(每个操作分别对应),其中2列包含一组可能的状态?
  z <- list()
  trim <- function (x) gsub("^\\s+|\\s+$", "", x)
  for(i in unique(data$Select.Actions))
  {
    z[[trim(i)]] <- data %>% filter(Select.Actions == i) %>% select(Current.State, Next.State) 
  }
  ###Condition must select 3 actions ####
  empiricala1<-z[1]
  empiricala2<-z[2]
  empiricala3<-z[3]

  #show(empirical) calculate transition probability from historical data
  em1<-as.data.frame(empiricala1)
  em2<-as.data.frame(empiricala2)
  em3<-as.data.frame(empiricala3)
  lis <- list(em1,em2,em3)
  tab1 <- table(em1)
  tab2 <- table(em2)
  tab3 <- table(em3)
  tab1<-addmargins(prop.table(table(em1$Current.State,em1$Next.State),1),2)
  tab2<-addmargins(prop.table(table(em2$Current.State,em2$Next.State),1),2)
  tab3<-addmargins(prop.table(table(em3$Current.State,em3$Next.State),1),2)

  transitionprob11<-p[,,1]<-prop.table(table(em1$Current.State,em1$Next.State),1)
  transitionprob12<-p[,,2]<-prop.table(table(em2$Current.State,em2$Next.State),1)
  transitionprob13<-p[,,3]<-prop.table(table(em3$Current.State,em3$Next.State),1)
  print(transitionprob11)
  print(transitionprob12)
  print(transitionprob13)