With and Within Function in R

  • With Function in R evaluate the R expression in an environment constructed locally by the data. It doesn’t create a copy of the data.
  • Within Function in R evaluates the R expression in an environment constructed locally and it creates a copy of data.

Syntax for with and within function in R:

  1. with(data,expression)
  1. within(data,expression)

 

Example of With Function in R:

Lets create a data frame as shown below

 # data frame creation

 df <- data.frame(a=1:5,b=2:6)
 df

output will be

     a    b

1  1    2

2   2   3

3   3   4

4   4   5

5   5   6

Lets demonstrate with function in R with an example

 # with function in R

 with(df, {c <- a + b; df;} )

In with function, while executing the expression in an environment. It doesn’t save the copy of data frame. so the addition of two columns will not be reflected in the output. So the output will be

     a    b

1   1    2

2   2   3

3   3   4

4   4   5

5   5   6

# with function in R

 df$c<-with(df, c <- a + b)
 df

 

In order to save the addition of two columns create an extra column with $ symbol as shown above. So the output of the data frame will be

     a    b    c

1   1    2    3

2   2    3    5

3   3    4    7

4   4    5    9

5   5    6    11

 

Example of within function in R:

# within function in R

within(df, {c <- a + b; df;} )

within function adds up the two column and stores it in a new column, so the output will be

    a    b    c

1   1   2    3

2   2   3    5

3   3   4    7

4   4   5    9

5   5   6   11

previous small with and within function in r                                                                                                                next small with and within function in r