从表中计算概率矩阵

时间:2017-03-01 01:06:30

标签: 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 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)

我将data.frame拆分为3个单独的列表,我想计算每个列表的转移概率矩阵。

  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)

但是当我运行它时,错误信息是找不到transitionprob1,transitionprob2和transitionprob3。 你能告诉我一下吗?

0 个答案:

没有答案