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



我有一个列表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

这里的任何帮助都将是感激的。谢谢。

我成功了:

# 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)

最新更新