Open In App

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

Last Updated : 01 Jun, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
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: Python3
# Creating list
df <- list("x1" = c(1, 2, 3),
           "x2" = c(4, 5, 6),
           "x3" = c(7, 8, 9))

with(df, x1 + x2 + x3)
Output:
[1] 12 15 18
Example 2: Python3
# Using mtcars dataset
with(mtcars, mean(mpg + cyl + disp))
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: Python3
# Creating a data frame
df <- list("x1" = c(1, 2, 3),
           "x2" = c(4, 5, 6))

within(df, x3 <- x1 + x2)
Output:
$x1
[1] 1 2 3

$x2
[1] 4 5 6

$x3
[1] 5 7 9
Example 2: Python3
# Using airquality dataset
aq <- within(airquality, {
    newOzone <- log(Ozone)
    cTemp <- round((Temp - 32) * 5/9, 1) # Fahrenheit to Celsius
    })

head(aq)
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

Next Article
Article Tags :

Similar Reads