[R] understanding with

Jeff Newmiller jdnewmil at dcn.davis.ca.us
Sat Sep 10 08:27:16 CEST 2016


Indeed, you don't have to write code with constructs you don't like, but 
you should be able to read it. Considerable effort under the label "scope" 
[1] is expended in programming language design specifically to allow 
re-use of variable names in different contexts. Because I do understand 
scope, I don't need to worry about whether variables with the same names 
might exist in different places in the program, much the same way I don't 
worry about multiple files called README that can be found in different 
directories on my hard disk... they are in different contexts, so there is 
no need to be confused between them or be disturbed that they exist. This 
does mean that if you want to read my code, you will also need to be 
comfortable with scope.

The with function is just helpful syntactic sugar for reducing repetitious 
typing of the name of the list/data frame that contains several objects 
you want to refer to in a single expression.

[1] https://en.wikipedia.org/wiki/Scope_(computer_science)

On Fri, 9 Sep 2016, Sarah Goslee wrote:

> Hi Carl,
>
> The duplicate names were to demonstrate the difference in search path
> and environment, since you appeared to be confused.
>
> If you dislike with, don't use it.
>
>
>
> On Fri, Sep 9, 2016 at 5:20 PM, Carl Sutton <suttoncarl at ymail.com> wrote:
>> Hi Sarah
>>
>> I see the difference, but pardon the big yawn, who writes code using the
>> same variable names in separate vectors and lists/data.frames?  That smacks
>> of bad planning in variable name selection and an invitation to disaster.
>> If it can happen, it will.  Looks to me there is a possible lack of planning
>> on the programmers part.  List variable names start with lst, data frames
>> with df, data tables dt, and vectors as descriptive as possible.  If any of
>> them are the same, I messed up.
>>
>> Carl Sutton CPA
>>
>>
>> On Friday, September 9, 2016 6:39 AM, Sarah Goslee <sarah.goslee at gmail.com>
>> wrote:
>>
>>
>>
>> Like others on the list I have no interest in wading through your
>> block of HTML-mangled text.
>>
>> But if your question is clearly stated by the subject line, then it's
>> quite straightforward.
>>
>> with() saves you typing and often increases code clarity by telling R
>> where to look for named variables
>>
>> # This example is best done in a clean R session
>>
>> # Given some R objects
>>
>> myLongDataframeName <- data.frame(x = runif(10), y = runif(10))
>>
>> x <- 1:10
>> y <- 1:10
>>
>> cor(myLongDataframeName$x, myLongDataframeName$y) # uses the data
>> frame columns named x and y
>> cor(x, y) # uses the R objects named x and y
>>
>> # Here's the magic of with():
>>
>> with(myLongDataframeName, cor(x, y)) # uses the data frame columns named x
>> and y
>>
>>
>> On Fri, Sep 9, 2016 at 12:46 AM, Carl Sutton via R-help
>> <r-help at r-project.org> wrote:
>>>  Hi I have been doing theR-exercises to improve my R programming
>>> capabilities.  Data.frame exercise4 showed me that I have a languageproblem.
>>> Yes, I am frustrated, but please don?t take this as acriticism of the R
>>> language.  Theroutines I have managed to write do marvelous things in a
>>> short period oftime.  I really want to do more, but thisis a steep rocky
>>> thick with underbrush hill that is not fun to climb.  But there are good
>>> resources.  Swirl is wonderful.  My thanks to the authors of thatpackage.
>>> Jared Lander?s R for Everyoneis a really good beginners book.  DataCamp,
>>> Coursera, all informative courses.  Yes I?m frustrated.  After a couple of
>>> years on and off takingclasses, reading books, reading stack overflow and
>>> r-help just about daily, Iam learning to almost crawl.  At one timeI thought
>>> I had advanced to walking but days like today show me I?m a toddlerabout to
>>> fall on his backside. Reading the manuals onCRAN is analogous to reading the
>>> tax code. Without a specific objective for motivation, reading them is
>>> either painfulor a certain cure for insomnia. Here's the problem Ireferred
>>> to at the beginning and my "solution". #  Exercise 4 fromR Exercises#
>>> Create a simpledata frame from 3 vectors. Order the entire data frame by
>>> the#  first column.df2 <- data.frame(a =5:1,b = letters[1:5], c =
>>> runif(5))order(df2$a) Naturally the orderfunction did nothing.  But I did
>>> read the help page and thought I followedit.  And there is no obvious
>>> environmentissue.  It?s a simple data.frame and Iwant to order it by one
>>> column.  Such asdf2 <- data.table(df2)setkey(df2, a).  Done. No fuss, no
>>> muss, no needing ?with?. Per "help"Description order returns apermutation
>>> which rearranges its first argument into ascending or descendingorder,
>>> breaking ties by further arguments. sort.list is the same, using onlyone
>>> argument.See the examples for howto use these functions to sort data frames,
>>> etc. Usage order(..., na.last =TRUE, decreasing = FALSE,    method =
>>> c("shell", "radix")) sort.list(x, partial =NULL, na.last = TRUE, decreasing
>>> = FALSE,        method = c("shell", "quick","radix"))Arguments ... a
>>> sequence of numeric,complex, character or logical vectors, all of the same
>>> length, or a classed Robject. Well, doesn't ... meanany legal object?  I
>>> gave it a legal object and got nada.  And the answerabsolutely has me
>>> screaming "Say What"df2[with(df2,order(a)),]  What's with "with? In Mr.
>>> Lander?s book, page 126, ?Here we used a new function, with.  This allows us
>>> to specify the columns of adata frame without having to specify the
>>> data.frame name each time.?  Great, I?m a horrible typist and will takeany
>>> and all typing shortcuts.  However, Idon?t use it because I don?t understand
>>> what it does.  Obviously it?s important, but I?m stuck on why or how I would
>>> use it. It is one function I donot use because I find it incomprehensible.
>>> To witEvaluate an R expressionin an environment constructed from data,
>>> possibly modifying (a copy of) theoriginal data. First of all, if I'm
>>> notmodifying data (or as a subset activity creating data), why am I doing
>>> whateverit is I'm doing? ("possibly modifying (a copy of) the
>>> originaldata.") Possibly?? Evaluate. According to the thesaurus a)
>>> assess(v), b) appraise, c) gage. OK, am I in a safe area? I'll evaluate
>>> that.  Do I desire future social contact with thisperson?  I'll evaluate
>>> that. In no way do I ever evaluatean equation.  I may attempt to solve it.
>>> I may do a computer programto do the calculations and return a result.  I
>>> will probably evaluate theresult as to whether or not it helps solve the
>>> problem.  Think in terms ofan income tax return.  But evaluate an R
>>> expression?  No clue whatthat might mean.  And that is my problemin a
>>> nutshell. The remainder of thedefinition is also obtuse.  an R expression in
>>> an environmentconstructed from data.  Why would one make an environment
>>> withoutdata?  Obviously I am missing thepoint.  My own created function
>>> makes a new environment, but I onlycreated it to crunch numbers.  If it
>>> doesn't crunch numbers it's useless. The point is, I do not understand the
>>> definitionof "with" and thus have no idea how to use it.  I guesscomputerese
>>> is analogous to taxlawese.  Familiar words have entirely different meanings.
>>> Carl Sutton CPA
>>
>>>
>>>        [[alternative HTML version deleted]]
>>
>>
>>
>> --
>> Sarah Goslee
>> http://www.functionaldiversity.org
>>
>
> ______________________________________________
> 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.

---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                       Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k



More information about the R-help mailing list