with() and within() Functions in R

with() and within() Functions in R, To evaluate an expression depending on a data frame, use R’s with() and inside() functions.

The syntax for these functions is as follows:

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

where:

data: The data frame name

expression: The expression to evaluate

The following is the distinction between the two functions:

The expression is evaluated with() without changing the underlying data frame.

Data Normalization in R »

inside() evaluates the expression and copies the original data frame into a new data frame.

With the following data frame, the following examples explain how to utilize each function in practice.

with() and within() Functions in R

Let’s create a data frame

df <- data.frame(x=c(13, 15, 15, 17, 15, 20),
                 y=c(22, 22, 20, 25, 29, 24))
df
  x  y
1 13 22
2 15 22
3 15 20
4 17 25
5 15 29
6 20 24

Example 1: Use with() Function

To multiply the values across the two columns in the data frame, we can use the with() function:

x and y values are multiplied

with(df, x*y)
[1]  286 330 300 425 435 480

The data frame’s values from column x and column y are multiplied together, yielding a vector of length 6.

Example 2: Use the 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, we can use the inside() function:

Multiply the x and y values and apply the results to the new column z.

Data Visualization with R-Scatter plots »

within(df, z <- x*y)
   x  y   z
1 13 22 286
2 15 22 330
3 15 20 300
4 17 25 425
5 15 29 435
6 20 24 480

The multiplication results are now placed in a new column called z.

It’s vital to remember that the within () function generates a copy of the original data frame but does not actually change it:

Let’s look at the original data frame

df
  x  y
1 13 22
2 15 22
3 15 20
4 17 25
5 15 29
6 20 24

To save the multiplication results indefinitely, we must assign them to a new data frame:

multiply the x and y values and save the results in a new data frame.

Deep Belief Networks and Autoencoders »

df1<- within(df, z <- x*y)

Let’s view the new data frame

df1
   x  y   z
1 13 22 286
2 15 22 330
3 15 20 300
4 17 25 425
5 15 29 435
6 20 24 480

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

two × 4 =