with, within

with(data, expr)
within(data, expr)
Perform R expressions using the items (variables) contained in a list or data frame. The within function will even keep track of changes made, including adding or deleting elements, and return a new object with these revised contents.
  • data – Typically a list or data frame, although other options exist for with.
  • expr – One or more expressions to evaluate using the contents of data (which are accessed directly), where the commands must be wrapped in braces if there is more than one expression to evaluate.

Examples. We load the marioKart data object from the openintro package, which provides information about 143 auctions for the Wii game, Mario Kart. (0) A new data set with two outliers is returned and saved to mk0. (1) A plot is constructed for the number of steering wheels included in the auction against the auction’s total price. Notice that the variables are accessed in the expressions without explicitly invoking the mk0 data frame. (2) An object is removed, so it will not be included in the returned value from within. (3) Other values can also be modified for the object returned from within. (4) Lastly, variables may be added to the outgoing object for within, as is done here with the end price of the auction.
> library(openintro)
> data(marioKart)
> names(marioKart)
 [1] "ID"         "duration"   "nBids"      "cond"      
 [5] "startPr"    "shipPr"     "totalPr"    "shipSp"    
 [9] "sellerRate" "stockPhoto" "wheels"     "title"     
> dim(marioKart)
[1] 143  12
> 
> #______ 0. Removing Two Outliers ______#
> mk0 <- marioKart[marioKart$totalPr < 100,]
> 
> 
> #______ 1. Create Plot ______#
> with(mk0, {
+            boxplot(totalPr ~ wheels)
+            points(wheels+1.1, totalPr, col=4)
+           })
> 
> 
> #______ 2. Remove One Column ______#
> mk2 <- within(mk0, rm(title))
> names(mk2)
 [1] "ID"         "duration"   "nBids"      "cond"      
 [5] "startPr"    "shipPr"     "totalPr"    "shipSp"    
 [9] "sellerRate" "stockPhoto" "wheels"    
> 
> 
> #______ 3. Change Values ______#
> mk0$totalPr[50]
[1] 59.88
> mk0$startPr[25]
[1] 0.01
> mk3 <- within(mk0, { # Would not typically do...
+                      # this is just an example
+                     totalPr[50] <- 88.59
+                     startPr[25] <- 85.00
+                    })
> mk3$totalPr[50]
[1] 88.59
> mk3$startPr[25]
[1] 85
> 
> 
> #______ 4. Constuct Auction End Price ______#
> mk4 <- within(mk0, endPrice <- totalPr - shipPr)
> all.equal(mk4$totalPr - mk4$shipPr, mk4$endPrice)
[1] TRUE
> names(mk4)
 [1] "ID"         "duration"   "nBids"      "cond"      
 [5] "startPr"    "shipPr"     "totalPr"    "shipSp"    
 [9] "sellerRate" "stockPhoto" "wheels"     "title"     
[13] "endPrice" 

Mario Kart Auctions: number of Wii wheels against total price

Leave a Reply