What is the difference between the with() and within() functions?

The with() function evaluates an R expression on one or more variables of a data frame and outputs the result without modifying the data frame. The within() function evaluates an R expression on one or more variables of a data frame, modifies the data frame, and outputs the result. Below we can see how these functions work using a sample data frame as an example:

df <- data.frame(a = c(1, 2, 3),  b = c(10, 20, 30))
print(df)

with(df, a * b)

print(within(df, c <- a * b))

Output:

  a  b
1 1 10
2 2 20
3 3 30

10  40  90
  a  b  c
1 1 10 10
2 2 20 40
3 3 30 90

Comments

Leave a Reply

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