I have a list sfa_out
with 8 stochastic frontier models stored inside.
I want to extract the efficiency estimate from each model using efficiencies()
function and store the extracted efficiency measure for all models in a single data frame. Doing so individually for each model is not a problem, however, I want to write a function that does it for all models.
My attempt using a for loop is below:
# 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()
}
However, doing so gives me the following error:
Error in `$<-.data.frame`(`*tmp*`, "i", value = list(col = c("GB0000365774", :
replacement has 139 rows, data has 0
Any help here would be appreciated. Thanks.
CodePudding user response:
The following did the trick for me:
# 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)