Evaluating an Expression in R Programming – with() and within() Function

with() function in R programming evaluates the expression in an environment constructed locally by the data and does not create a copy of the data.

Syntax: with(data, expr)

Parameters:

data represents dataset to be used
expr represents formula or expression to be evaluated

Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

# Creating list
df <- list("x1" = c(1, 2, 3),
           "x2" = c(4, 5, 6),
           "x3" = c(7, 8, 9))
  
with(df, x1 + x2 + x3)

chevron_right


Output:

[1] 12 15 18

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Using mtcars dataset
with(mtcars, mean(mpg + cyl + disp))

chevron_right


Output:

[1] 257

within() Function

within() function in R programming evaluates the expression in a locally created environment and modifies the copy of the data unlike with() function.

Syntax: within(data, expr)

Parameters:
data represents dataset to be used
expr represents formula or expression to be evaluated

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Creating a data frame
df <- list("x1" = c(1, 2, 3),
           "x2" = c(4, 5, 6))
  
within(df, x3 <- x1 + x2)

chevron_right


Output:

$x1
[1] 1 2 3

$x2
[1] 4 5 6

$x3
[1] 5 7 9

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Using airquality dataset
aq <- within(airquality, {
    newOzone <- log(Ozone)
    cTemp <- round((Temp - 32) * 5/9, 1) # Fahrenheit to Celsius
    })
  
head(aq)

chevron_right


Output:

   Ozone Solar.R Wind Temp Month Day cTemp newOzone
1    41     190  7.4   67     5   1  19.4 3.713572
2    36     118  8.0   72     5   2  22.2 3.583519
3    12     149 12.6   74     5   3  23.3 2.484907
4    18     313 11.5   62     5   4  16.7 2.890372
5    NA      NA 14.3   56     5   5  13.3       NA
6    28      NA 14.9   66     5   6  18.9 3.332205



My Personal Notes arrow_drop_up

Recommended Posts:


Blockchain Enthusiast

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.