0

I am worried if someone can help me for getting output from ifelse() function in R. I am using mtcars dataset. I wants if condition is TRUE then the command should return a data frame and if condition is FALSE then the command should return a NULL object. I shall further use this command in geom_point() function for argument data. When the condition in ifelse is FALSE the output will be a NULL object for data argument in geom_point() function with no points. The command I have used is given below but it resulted in error:

data("mtcars")
ifelse(dim(filter(mtcars, mpg < 10))[1] > 0, 
       as.data.frame(filter(mtcars, mpg > 10)), 
       as.null(filter(mtcars, mpg < 10)))

Here is the error: Error in ans[npos] <- rep(no, length.out = len)[npos] : replacement has length zero In addition: Warning message: In rep(no, length.out = len) : 'x' is NULL so the result will be NULL

However, if I run individual commands like as.data.frame(filter(mtcars, mpg > 10)) and as.null(filter(mtcars, mpg < 10)) the output is okay. But using it within the ifelse function, it shows an error for the second command (NULL object).

My concern is that if condition is FALSE the ifelse function should return the output as NULL, so this could be used in geom_point() function for the data argument to hide points from the plot.

I would be really grateful for your assistance in this matter.

Thanks

Farhan
  • 57
  • 5
  • 1
    Try with `if`-`else` instead of `ifelse`: `if (nrow(filter(mtcars, mpg < 10) > 0)) filter(mtcars, mpg > 10) else NULL` – stefan Sep 21 '22 at 06:25
  • Thank you very much for your response; it has resolved the issue I was having. – Farhan Sep 21 '22 at 06:41

0 Answers0