我有 198 个独特的数据集,每个数据集中的所有变量都是相同的。我想对每个数据集进行相同的分析(见下文(。 从每次进行的分析中,我想从模型结果中提取系数并将其存储在一个表中。为此,我编写了以下代码:
one_table <- data.frame() #dataframe I will use to store results in later
for(i in 1:198){
load(file = paste("Dataset_",i,".RData",sep = "")) #loads a dataset
Dataset = get(paste0("Dataset_", i)) #renames the loaded Dataset_i to Dataset, important for model below
model_result = try(summary(lme(A ~ B + C + B*C + D + E, random = ~1|company,na.action=na.omit,
control=lmeControl(opt='optim'),method='REML',
data=Dataset,correlation = corAR1())),silent=TRUE) #model
coefficients = coef(model_result) #extracts coefficients from model results
coefficients_df <- as.data.frame(coefficients) #puts coefficients into a table
one_table <- rbind(one_table, coefficients_df) #updates table with each iteration of i
现在,代码一直工作到数据集编号 96,我收到以下错误:$ operator is invalid for atomic vectors.
我不太确定如何继续,此错误指的是什么?
编辑:我想我发现了问题。该模型无法在编号为 97 的数据集上运行,我收到以下与 B*C 相关的错误
[1] "Error in logLik.reStruct(object, conLin) : n NA/NaN/Inf in foreign function call (arg 3)n"
attr(,"class")
[1] "try-error"
attr(,"condition")
<simpleError in logLik.reStruct(object, conLin): NA/NaN/Inf in foreign function call (arg 3)>
发生 B*C 错误是因为在编号为 97 的数据集中错误地计算了一个变量 - 愚蠢的错误!
注意:您还可以将模型结果存储在列表中
list.res.H = list()
for(i in 1:198){
load(file = paste("Dataset_",i,".RData",sep = "")) #loads a dataset
Dataset = get(paste0("Dataset_", i)) #renames the loaded Dataset_i to Dataset, important for model below
model_result = try(summary(lme(A ~ B + C + B*C + D + E, random = ~1|company,na.action=na.omit,
control=lmeControl(opt='optim'),method='REML',
data=Dataset,correlation = corAR1())),silent=TRUE) #model
list.res.H[[i]] = coef(model_result) #extracts coefficients from model results
}