[英]R project: loop breaks after lm gives error
I want to automatically run linear regressions and save the results. 我想自动运行线性回归并保存结果。 The beta coefficients generated by R project will be later used as parameters for further computations.
R project生成的beta系数将在以后用作进一步计算的参数。
This an example of my data layout: 这是我的数据布局的一个示例:
id |x_2000|x_2001|x_2002|y_2000|y_2001|y_2002|z_2000|z_2001|z_2002
1 |20 |NA |6 |90 |NA |80 |54 |NA |10
2 |50 |NA |10 |50 |NA |50 |60 |NA |40
3 |4 |NA |1 |5 |NA |10 |30 |NA |120
x is value x and the number behind it represents a year. x是值x,其后的数字表示年份。 The same logic applies to the other variables y and z.
相同的逻辑适用于其他变量y和z。
To run the linear regressions, I have created a loop. 为了运行线性回归,我创建了一个循环。 I use the following code to loop through the variables and to run a regression for each year.
我使用以下代码循环遍历变量并每年进行回归。
for (i in 2000:2002){
X_COLUMN <- c(paste0("x_",i))
Y_COLUMN <- c(paste0("y_",i))
Z_COLUMN <- c(paste0("z_",i))
result.lm <- lm(as.formula(paste("formula=",X_COLUMN,"~",Y_COLUMN,"+",Z_COLUMN,"-1")), data=data_for_regression)
b1 <- rbind(b1, c(x,i,coef(result.lm)[1]))
b2 <- rbind(b2, c(x,i,coef(result.lm)[2]))
}
For 2000 everything works well, however when the loop continues to year 2001 it hits the NA values. 对于2000年,一切工作正常,但是当循环持续到2001年时,它将达到NA值。 This results in a error message:
这将导致错误消息:
Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, …) : 0 (non-NA) cases
lm.fit(x,y,offset = offset,singular.ok = singular.ok,…)中的错误:0(非NA)
Logical, because there is no complete case for year 2001. The result is that the loop breaks. 逻辑上,因为没有2001年的完整案例。结果是循环中断。 However, I don't want it to break but to continue to the next year.
但是,我不想打破它,而是继续到明年。
Any idea how to fix this? 任何想法如何解决这个问题?
How about using a try
statement 如何使用
try
语句
for (i in 2000:2002){
X_COLUMN <- c(paste0("x_",i))
Y_COLUMN <- c(paste0("y_",i))
Z_COLUMN <- c(paste0("z_",i))
try({
result.lm <- lm(as.formula(paste("formula=",X_COLUMN,"~",Y_COLUMN,"+",Z_COLUMN,"-1")), data=data_for_regression)
b1 <- rbind(b1, c(x,i,coef(result.lm)[1]))
b2 <- rbind(b2, c(x,i,coef(result.lm)[2]))
}, silent=T)
}
or an tryCatch
或
tryCatch
for (i in 2000:2002){
X_COLUMN <- c(paste0("x_",i))
Y_COLUMN <- c(paste0("y_",i))
Z_COLUMN <- c(paste0("z_",i))
tryCatch({
result.lm <- lm(as.formula(paste("formula=",X_COLUMN,"~",Y_COLUMN,"+",Z_COLUMN,"-1")), data=data_for_regression)
b1 <- rbind(b1, c(x,i,coef(result.lm)[1]))
b2 <- rbind(b2, c(x,i,coef(result.lm)[2]))
}, error=function(e) {
b1 <- rbind(b1, c(x,i,NA))
b2 <- rbind(b2, c(x,i,NA))
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.