How to Use with() and within() Functions in R


The with() and within() functions in R can be used to evaluate some expression based on a data frame.

These functions use the following syntax:

with(data, expression)
within(data, expression)

where:

  • data: The name of the data frame
  • expression: The expression to evaluate

Here’s the difference between the two functions:

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

The following examples show how to use each function in practice with the following data frame:

#create data frame
df <- data.frame(x=c(3, 5, 5, 7, 6, 10),
                 y=c(2, 2, 0, 5, 9, 4))

#view data frame
df

   x y
1  3 2
2  5 2
3  5 0
4  7 5
5  6 9
6 10 4

Example 1: Use with() Function

We can use the following with() function to multiply the values between the two columns in the data frame:

#multiply values between x and y
with(df, x*y)

[1]  6 10  0 35 54 40

The values from column x and column y in the data frame are multiplied together and the result is a vector of length 6.

Example 2: Use within() Function

We can use the following within() function to multiply the values between the two columns in the data frame and assign the results to a new column in the data frame:

#multiply values in x and y and assign results to new column z
within(df, z <- x*y)

   x y  z
1  3 2  6
2  5 2 10
3  5 0  0
4  7 5 35
5  6 9 54
6 10 4 40

The results of the multiplication are now stored in a new column named z.

It’s important to note that the within() function creates a copy of the original data frame but does not actually modify the original data frame:

#view original data frame
df

   x y
1  3 2
2  5 2
3  5 0
4  7 5
5  6 9
6 10 4

To permanently store the results of the multiplication, we must assign the results to a new data frame:

#multiply values in x and y and assign results to new data frame
df_new <- within(df, z <- x*y)

#view new data frame
df_new

   x y  z
1  3 2  6
2  5 2 10
3  5 0  0
4  7 5 35
5  6 9 54
6 10 4 40

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Add a Column to a Data Frame in R
How to Add an Empty Column to a Data Frame in R
How to Sort a Data Frame by Column in R

Leave a Reply

Your email address will not be published.