With function in R programming language

With function in R programming language

Hello guys, what’s up? In this R programming tutorial I’ll teach you how to use with function in r. Let’s first have a look at the basic R syntax and the definition of with():

Basic Syntax of with function in r:
with(data, expr, ...)

data: data to use for constructing an environment. For the default with method this may be an environment, a list, a data frame, or an integer as in system call.

Definition of with()

The with()  function evaluates an R expression in an environment constructed from data, possibly modifying the original data. It doesn’t create a copy of the data. withis a general purpose wrapper to let you use any function as if it had a data argument.

When to use with
Use with whenever you like interactively (R console) and in R scripts to save typing and make your code clearer. The more frequently you would need to re-type your data frame name for a single command (and the longer your data frame name is!), the greater the benefit of using with.
When to avoid with
Many functions that have a data argument use it for more than just easier syntax when you call it. Most modeling functions (like lm), and many others too (ggplot!) do a lot with the provided data. If you use with instead of a dataargument, you’ll limit the features available to you. If there is a data argument, use the data argument, not with.

Example 1:
Before we can apply the with function, we need to create an example data frame (Data frame is a two dimensional data structure in R) in R

data <- data.frame(x1 = c(5, 3, 1),     # Create example data frame
                   x2 = c(4, 3, 1))
data                                    # Print data to RStudio console
With function in R programming language
Table: Example of Data Frame in R.

The Table has two columns and three rows which contain. Now, we are going to compute the sum of our two variables by applying with function in r:

with(data, x1 + x2)                     # Apply with function
# 9 6 2

Example 2: with Function in R



  Time demand
1    1    8.3
2    2   10.3
3    3   19.0
4    4   16.0
5    5   15.6
6    7   19.8

[1]  9.3 11.3 20.0 17.0 16.6 20.8

Example3 of With Function in R:Let’s create a data frame as shown below

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

Output looks like below

    a   b
1   1   2

2   2   3

3   3   4

4   4   5

5   5   6

Let’s demonstrate with function in R with an example

# with function in R
 df$c<-with(df, c <- a + b)

After executing this, our output looks like below

    a    b    c

1   1    2    3

2   2    3    5

3   3    4    7

4   4    5    9

5   5    6    11

Today we have learned about with function in R programming language. I hope you guys understood everything clearly. So, guys, that’s all about for today. Later we will discuss another topic of r programming language. Till then, take care. Happy Coding

Post a Comment