如何在R中使用for循环选择excel表

时间:2016-02-27 00:16:33

标签: r rexcel

我希望我自动开发的应用程序转到Excel工作表并计算转换概率矩阵。

 action<-actions
    state<-states
    p<-array(0,c(length(state),length(state),length(action)))
    colnames(p)=state
    rownames(p)=state
    # transition probability matrix based on the action that we have choosen
    empiricala1<-read.xlsx("www/dynamic model.xlsx",1)
    empiricala2<-read.xlsx("www/dynamic model.xlsx",2)


    #show(empirical) calculate transition probability from historical data
    em1<-as.data.frame(empiricala1)
    em2<-as.data.frame(empiricala2)
    tab1 <- table(em1)
    tab2 <- table(em2)

    tab1<-addmargins(prop.table(table(em1$current,em1$nextstate),1),2)
    tab2<-addmargins(prop.table(table(em2$current,em2$nextstate),1),2)
    transitionprob1<-p[,,1]<-prop.table(table(em1$current,em1$nextstate),1)
    transitionprob2<-p[,,2]<-prop.table(table(em2$current,em2$nextstate),2)
    print(transitionprob1)
    print(transitionprob2)


    for(i in 1:length(action)){

      p[,,i]<-prop.table(table(em[i]$current,em[i]$nextstate),i)

    }

我得到的错误如下:

Error in em[i] : object of type 'closure' is not subsettable

如何解决此问题。

1 个答案:

答案 0 :(得分:1)

好的,那么扩大评论......

您有两个数据框em1em2。您似乎希望对两个数据框应用相同的操作(例如table(em1)table(em2)。这写起来非常繁琐,特别是一旦您获得更多变量。

你试图做的是:

for (i in 1:2) em[i]

问题在于您没有得到em1em2。相反,您得到em[1]em[2],因此指的是em对象(开头不存在)。

有几种方法可以解决这个问题。

<强> 1。将数据框移动到列表

lis <- list(em1, em2)

这样,您可以使用*apply系列或for循环遍历列表:

sapply(lis, nrow)
for (i in 1:length(lis)) nrow(lis[[i]])

<强> 2。使用get

另一种选择是使用get,它允许你提供一个字符串,然后它将返回该字符串中描述的变量。

vec <- c("em1","em2")
sapply(vec, function(x) nrow(get(x)))

请注意,通常不鼓励使用get。我也会选择第一个选项。