alice in wond-r-land,loops, eval(parse()), & the next level in r
DESCRIPTION
Alice in Wond-R-land,loops, eval(parse()), & the next level in R. Looping in R is an important skill to develop. Loops tell R to do the same thing many times until R reaches the end. Each loop, the index is updated. Here is a loop of length 2. for (k in 1:2){. k=2. k=1. Examples of loops. - PowerPoint PPT PresentationTRANSCRIPT
Alice in Wond-R-land,loops, eval(parse()), & the next level in R
Looping in R is an important skill to develop
Loops tell R to do the same thing many times until R reaches the end. Each loop, the index is
updated. Here is a loop of length 2.
for (k in 1:2){
k=2
k=1
Examples of loops
Alice meets the White KnightKnight: Let me sing you a song to comfort you… The name of the song is called "Haddocks’ Eyes."
Alice: Oh, that's the name of the song, is it?
Knight: No, you don't understand, That’s what the name is called. The name really is "The Aged Aged Man."
Alice: Then I ought to have said "That's what the song is called"?
Knight: No, you oughtn't: that's quite another thing! The song is called "Ways and Means": but that's only what it's called, you know!
Alice: Well, what is the song, then?
Knight: I was coming to that. The song really is "A-sitting On A Gate": and the tune's my own invention.
Distinction between the object itself and what it is called
• Cheese is derived from milk. Most people like to eat it.
• "Cheese" is derived from a word in Old English. It has six letters.
Distinction between the object itself and what it is called
• USArrests is a data.frame with 50 rows and 4 columns
• “USArrests” is a string with 9 characters.
Distinction between the object itself and what it is called
• How do we take “USArrests”, the character string, and tell R to treat as USArrests, the data.frame?
• More generally: how do we tell R to treat any character strings (created using, e.g., paste) and evaluate it as though it were typed in by the user?
Eval & Parse
• parse(text=“FUN”): parse tells R to treat “FUN” as if it were typed in - FUN - by the user I.e., to change it from what the object is called to what it is.
• eval(parse()): eval tells R to evaluate the parsed statement. I.e., its like pressing <enter> after typing into R.
Why are they useful?• Often, you need to build commands
dynamically, e.g., within a for() loop. These commands may be to automate object assignment, alter titles, place statistics in graphs, analyzing different data subsets, and so forth.
• Along with system() and function(), for() loops and eval(parse()) are two of the most important new abilities you’ll gain in becoming an R wizard.
Today, you’re graduating to the next level of R!