[R] if/else help

David Winsemius dwinsemius at comcast.net
Wed Sep 21 08:58:23 CEST 2016

> On Sep 20, 2016, at 12:31 PM, Crombie, Burnette N <bcrombie at utk.edu> wrote:
> If a data.frame (r4) does not exist in my R environment, I would like to create it before I move on to the next step in my script. How do I make that happen?  Here is what I want to do from a code perspective:
> if (exists(r4))
> {
> is.data.frame(get(r4))
> }
> else
> {
> a <- 0, b <- 0, c <- 0, d <- "x", r4 <- data.frame(cbind(a,b,c,d))
> }
> Thanks for your help,
> B
> 	[[alternative HTML version deleted]]

Please, please, please, do not encourage people to use the construction:


...and learn to distrust whatever misguided example you learned it from. (Yes, I know there is one in the help pages but that is an exception to the rule.)

There is no reason to use it. It would be much clearer to do this:

r4 <- data.frame(a = 0, b = 0, c = 0, d = "x")    # only one column is factor-class.

If you did it your way you would have gotten four columns of factors, (first cbind() creates a character matrix, and then data.frame() creates factors)  ... which does not appear to be what you expected.

And ... as always has been the case on Rhelp, ... learn to post in plain text.

> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius
Alameda, CA, USA

More information about the R-help mailing list