[英]Skip Line if Error Occurs within Function in R
I am currently trying to solve a bug but believe the data I am working with may be too complex and cause errors that shouldn't normally occur.我目前正在尝试解决一个错误,但我认为我正在使用的数据可能过于复杂并导致通常不应该发生的错误。 I've written a function, and was hoping to add a try
or tryCatch
statement to skip the error if it occurs.我写了一个 function,并希望添加一个try
或tryCatch
语句来跳过错误,如果它发生。 I currently have:我目前有:
library(glmnet)
foo <- function(data, ols_ps = TRUE, index) {
# index is the bootstrap sample index
x <- data[index, -1]
y <- data[index, 1]
ridge <- cv.glmnet(x, y, alpha = 0)
## The intercept estimate should be dropped.
weights <- as.numeric(coef(ridge, s = ridge$lambda.min))[-1]
# alpha=1, lasso
alasso <- cv.glmnet(x, y, alpha = 1,
penalty.factor = 1 / abs(weights))
# Select nonzero coefficients
coef <- as.vector(coef(alasso, s = alasso$lambda.min,
exact = TRUE, x = x, y = y,
penalty.factor = 1 / abs(weights)))[-1]
if (ols_ps == TRUE) {
coef_nonzero <- coef != 0
new_x <- tryCatch(x[, coef_nonzero, drop = FALSE],
error=function(e) NA)
if (!any(is.na(new_x)) & ncol(new_x) > 0) {
ls.obj <- lm(y ~ new_x)
ls_coef <- (ls.obj$coefficients)[-1]
coef[coef_nonzero] <- ls_coef
} else {
coef <- coef
}
} else {
coef <- coef
}
return(coef)
}
which normally works and works on most datasets.这通常适用于大多数数据集。 I think the error may be coming from a complex dataset.我认为错误可能来自复杂的数据集。 Is it possible to skip OLS if I get the below error?如果我收到以下错误,是否可以跳过 OLS?
"Error in x[, coef_nonzero, drop = FALSE]: \n (subscript) logical subscript too long\n" attr(,"class") "x[, coef_nonzero, drop = FALSE] 中的错误:\n (下标) 逻辑下标太长\n" attr(,"class")
Here is a minimal working example per request.这是每个请求的最小工作示例。
set.seed(123)
matrix <- matrix(runif(1000), ncol=10)
boot(matrix,foo,R=50)
Thanks in advance.提前致谢。
Maybe like this?也许像这样?
foo <- function(data, index) {
# index is the bootstrap sample index
x <- data[index, -1]
y <- data[index, 1]
ridge <- cv.glmnet(x, y, alpha = 0)
## The intercept estimate should be dropped.
weights <- as.numeric(coef(ridge, s = ridge$lambda.min))[-1]
# alpha=1, lasso
alasso <- cv.glmnet(x, y, alpha = 1,
penalty.factor = 1 / abs(weights))
# Select nonzero coefficients
coef <- as.vector(coef(alasso, s = alasso$lambda.min,
exact = TRUE, x = x, y = y,
penalty.factor = 1 / abs(weights)))[-1]
coef_nonzero <- coef != 0
new_x <- tryCatch(x[, coef_nonzero, drop = FALSE],
error=function(e) NA)
if (!any(is.na(new_x))) {
ls.obj <- lm(y ~ new_x)
ls_coef <- (ls.obj$coefficients)[-1]
coef[coef_nonzero] <- ls_coef
}
return(coef)
}
The problem is that we have no case when it fails so far.问题是到目前为止我们还没有失败的案例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.