[R] Different output for "if else" and "ifelse" that I don't understand

Marc Girondot marc_grt at yahoo.fr
Fri Apr 28 11:21:18 CEST 2017


Dear list-members,

During the test phase of a function, I run it interactively (in Rstudio) 
and the ... produces an error. Then I use this to read it:

if (class(try(list(...), silent=TRUE))=="try-error") p3p <- list() else 
p3p <- list(...)

It works fine; interactively I will get

 > if (class(try(list(...), silent=TRUE))=="try-error") p3p <- list() 
else p3p <- list(...)
 > p3p
list()

and within a function I will get a list with the ... value. Perfect.

I wanted to simplify the line by doing:

p3p <- ifelse(class(try(list(...), silent=TRUE))=="try-error", list(), 
list(...))

In interactive mode, it works but within a function, I don't get the 
names of the parameters. I don't understand the logic behind this 
difference. Have you an idea ?

Thanks

Marc


 > Try1 <- function(...) {
+   if (class(try(list(...), silent=TRUE))=="try-error") p3p <- list() 
else p3p <- list(...)
+   return(p3p)
+ }
 > Try1(k=100)
$k
[1] 100

 > Try1()
list()
 > Try2 <- function(...) {
+   p3p <- ifelse(class(try(list(...), silent=TRUE))=="try-error", 
list(), list(...))
+   return(p3p)
+ }
 > Try2(k=100)
[[1]]
[1] 100

 > Try2()
[[1]]
NULL



More information about the R-help mailing list