[R] if/else help

Crombie, Burnette N bcrombie at utk.edu
Wed Sep 21 16:59:56 CEST 2016

Thanks very much for your detailed reply to my post.  Very helpful/useful tool(s) you’ve provide me.  Best wishes, B.

From: William Dunlap [mailto:wdunlap at tibco.com]
Sent: Wednesday, September 21, 2016 10:48 AM
To: Crombie, Burnette N <bcrombie at utk.edu>
Cc: r-help at r-project.org
Subject: Re: [R] if/else help

If you write your code as functions you can avoid the nasty 'if(exists("x"))x<-...' business this by writing default values for
arguments to your function.   They will be computed only when
they are used.  E.g.,
analyzeData <- function(a=0, b=0, c=0, d="x", r4 = data.frame(a, b, c, d)) {
> analyzeData(c=101:102)
       a           b           c         d
 Min.   :0   Min.   :0   Min.   :101.0   x:2
 1st Qu.:0   1st Qu.:0   1st Qu.:101.2
 Median :0   Median :0   Median :101.5
 Mean   :0   Mean   :0   Mean   :101.5
 3rd Qu.:0   3rd Qu.:0   3rd Qu.:101.8
 Max.   :0   Max.   :0   Max.   :102.0
> analyzeData(r4=data.frame(a=10:11,b=20:21,c=30:31,d=c("x","y")))
       a               b               c         d
 Min.   :10.00   Min.   :20.00   Min.   :30.00   x:1
 1st Qu.:10.25   1st Qu.:20.25   1st Qu.:30.25   y:1
 Median :10.50   Median :20.50   Median :30.50
 Mean   :10.50   Mean   :20.50   Mean   :30.50
 3rd Qu.:10.75   3rd Qu.:20.75   3rd Qu.:30.75
 Max.   :11.00   Max.   :21.00   Max.   :31.00

Bill Dunlap
TIBCO Software
wdunlap tibco.com<http://tibco.com>

On Tue, Sep 20, 2016 at 12:31 PM, Crombie, Burnette N <bcrombie at utk.edu<mailto: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))
a <- 0, b <- 0, c <- 0, d <- "x", r4 <- data.frame(cbind(a,b,c,d))

Thanks for your help,

        [[alternative HTML version deleted]]

R-help at r-project.org<mailto:R-help at r-project.org> mailing list -- To UNSUBSCRIBE and more, see
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

	[[alternative HTML version deleted]]

More information about the R-help mailing list