【问题标题】:How select the excel sheet using for loop in R [closed]如何在R中使用for循环选择excel表[关闭]
【发布时间】:2025-12-30 17:30:07
【问题描述】:

我希望我正在开发的应用程序自动转到 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

我该如何解决这个问题。

【问题讨论】:

  • em 声明在哪里?至于您的错误,请参阅?em
  • 解释器认为em是一个函数。
  • 我想在 'em1
  • lis &lt;- list(em1,em2); for (i in 1:length(lis)) p[,,i]&lt;-prop.table(table(lis[[i]][,"current"],lis[[i]][,"nextstate"]),i)
  • 因为你使用了for-loop,所以你想迭代一些东西。你尝试了em[i],但这只是意味着你有一个向量em,并且想要迭代它的元素(em[1]em[2]),而不是你想要em1em2等。为什么会发生错误。为了解决这个问题,我只是将em1em2 放在一个列表中,以便您可以迭代列表。

标签: r rexcel


【解决方案1】:

好的,接下来就扩展 cmets...

您有两个数据框 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-loop 等对列表进行迭代:

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。我也会选择第一个选项。

【讨论】: