In R we use with() and within() function to evaluate expression based on dataframe.

The following methods show how you can do it with syntax.

Method 1: Use with() Function

with(df,expression)

Method 2: Use within() Function

within(df,expression)

expression : expression to evaluate

The with() evaluates the expression without modifying the original data frame. The within() evaluates the expression and creates a copy of the original data frame.

Let’s first create data frame to apply expression:

# Define dataframe
df <- data.frame(Humidity=c(78,79,75,79,74,81,82,73),
                 Temperature=c(12,9,14,13,18,28,22,23),
                 Pressure=c(20,25,27,29,30,32,39,40))

# Print data frame
print(df)                 

Output:

  Humidity Temperature Pressure
1       78          12       20
2       79           9       25
3       75          14       27
4       79          13       29
5       74          18       30
6       81          28       32
7       82          22       39
8       73          23       40

The output shows dataframe that created using data.frame() function.

Use with() Function

We can use with() function to multiply two variables of dataframe:

# Define dataframe
df <- data.frame(Humidity=c(78,79,75,79,74,81,82,73),
                 Temperature=c(12,9,14,13,18,28,22,23),
                 Pressure=c(20,25,27,29,30,32,39,40))

# Multiply values between Humidity and Temperature
with(df, Humidity*Temperature)

Output:

[1]  936  711 1050 1027 1332 2268 1804 1679

This with() function multiply temperature and humidity column of dataframe and create vector with out affecting original dataframe.

Use within() Function

Now use within() function to multiply two variables of data frame and assign results to new column of dataframe.

# Define dataframe
df <- data.frame(Humidity=c(78,79,75,79,74,81,82,73),
                 Temperature=c(12,9,14,13,18,28,22,23),
                 Pressure=c(20,25,27,29,30,32,39,40))

# Multiply values between Temperature and Pressure
within(df, a <- Temperature*Pressure)

Output:

Humidity Temperature Pressure   a
1       78          12       20 240
2       79           9       25 225
3       75          14       27 378
4       79          13       29 377
5       74          18       30 540
6       81          28       32 896
7       82          22       39 858
8       73          23       40 920

This new column assign to copy of original dataframe with out affecting original dataframe.