The following code is misbehaving. When I run it inside RStudio to test it, it's fine. I get a value for custom_vars which makes sense. As soon as I try to run this code with Knit, it returns the error every time.
I've tried playing aorund with the scope of custom_vars, but that doesnt' work either.
report_params <- "-summary-private-room-tenure-minmax-map-Analyse newVar group-Analyse oldVar group"
custom_vars <- tryCatch(
{
a <- report_params
a <- as.list(strsplit(a, "-")[[1]])
a <- str_subset(a, pattern = "Analyse.*.group")
if (length(a) > 0) {
a <- sapply(strsplit(a, split=' group' , fixed=TRUE), function(x) (x[1]))
a <- sapply(strsplit(a, split='Analyse ', fixed=TRUE), function(x) (x[2]))
custom_vars <- c(a) # no return in try code!
} else {
ret <- c("zero legth")
return( ret )
}
}, error=function(e) {
ret <- c("error")
return( ret )
}
)
If I chop out the trycatch, it works fine again. I've tried everything I can think of. This makes no sense whatsoever.
a <- params$report_params
a <- as.list(strsplit(a, "-")[[1]])
a <- stringr::str_subset(a, pattern = "Analyse.*.group")
if (length(a) > 0) {
a <- sapply(strsplit(a, split=' group' , fixed=TRUE), function(x) (x[1]))
a <- sapply(strsplit(a, split='Analyse ', fixed=TRUE), function(x) (x[2]))
custom_vars <- c(a) # no return in try code!
} else {
custom_vars <- c("zero legth")
# return( ret )
}
CodePudding user response:
This is no function
, no need for return
. The return
caused an error an triggered the e
rror function in tryCatch
.
custom_vars <- tryCatch({
a <- report_params
a <- as.list(strsplit(a, "-")[[1]])
a <- stringr::str_subset(a, pattern="Analyse.*.group")
if (length(a) > 0) {
a <- sapply(strsplit(a, split=' group', fixed=TRUE), function(x) x[1])
sapply(strsplit(a, split='Analyse ', fixed=TRUE), function(x) x[2])
} else {
"zero legth"
}
}, error=function(e) "error")
custom_vars
# [1] "newVar" "oldVar"