R语言 从随机前沿模型列表中提取输出并存储在单个数据框中

hrysbysz  于 2023-01-28  发布在  其他
关注(0)|答案(1)|浏览(142)

我有一个列表sfa_out,里面存储了8个随机前沿模型。
我想使用efficiencies()函数从每个模型中提取效率估计值,并将提取的所有模型的效率度量值存储在一个数据框中。为每个模型单独执行此操作不成问题,但是,我想编写一个函数为所有模型执行此操作。
我尝试使用一个for循环如下:

# define an empty data frame
eff_out <- data.frame()

# write a for loop for each i model in the list "sfa_out"
for(i in 1:length(sfa_out$models)) {
  eff_out$i = as.data.frame(efficiencies(sfa_out$models[[i]])) %>%

# the code below pivots the data frame so that three columns are "col", "year" and "efficiency"
  
    mutate(col = row.names(efficiencies(sfa_out$models[[i]]))) %>%
    pivot_longer(cols = 1:23,
                 names_to = "year",
                 values_to = "efficiency") %>%
    drop_na()
}

但是,这样做会产生以下错误:

Error in `$<-.data.frame`(`*tmp*`, "i", value = list(col = c("GB0000365774",  : 
  replacement has 139 rows, data has 0

任何帮助都将不胜感激。谢谢。

l7mqbcuq

l7mqbcuq1#

下面的代码对我来说很有用:

# create a new list by extracting only models from the list sfa_out
newlist <- as.list(sfa_out$models)

# define a function which gets the required output from each model

outputs <- function(newlist) {
  
# create an empty data.frame
  eff_out <- data.frame()
  
# loop through each model in the newlist
  for(i in 1:length(newlist)) {

      eff <- as.data.frame(efficiencies(newlist[[i]])) %>%
      mutate(col = row.names(efficiencies(newlist[[i]]))) %>%
      pivot_longer(cols = 1:23,
                   names_to = "year",
                   values_to = "efficiency") %>%
      drop_na()

# current model output  
   model_output <- data.frame(eff)
  
# append output to empty dataset we created before
   eff_out <- rbind(eff_out, model_output)
  }
  return(eff_out)
}
# apply the function to the list containing models
sfa_eff_outputs <- outputs(newlist)

相关问题