Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

The post How to Use the sweep Function in R? appeared first on finnstats.

If you are interested to learn more about data science, you can find more articles here finnstats.

How to Use the sweep Function in R?, The sweep() function in R allows you to carry out various operations on a matrix’s rows or columns.

The basic syntax used by this function is as follows.

`sweep(x, MARGIN, STATS, FUN)`

where:

x: Name of the matrix

MARGIN: The margin on which to run the function (1 = rows, 2 = columns)

STATS: The value(s) to use in the function

FUN: The function to perform

## How to Use the sweep Function in R

The sweep() function is used in many R settings in the examples that follow.

### Example 1: Perform an operation on rows using sweep()

The sweep() function can be used to add a particular number to the values in each row of the matrix by using the following code.

Let’s define a matrix

`mat <- matrix(1:15, nrow=5)`

Now we can view the matrix

```mat
[,1] [,2] [,3]
[1,]    1    6   11
[2,]    2    7   12
[3,]    3    8   13
[4,]    4    9   14
[5,]    5   10   15```

add specific numbers to each row

```sweep(mat, 1, c(5, 10, 10, 10, 10), "+")
[,1] [,2] [,3]
[1,]    6   11   16
[2,]   12   17   22
[3,]   13   18   23
[4,]   14   19   24
[5,]   15   20   25```

Here’s how the sweep() function worked in this scenario.

5 was added to each value in the first row

10 was added to each value in the second row and so on.

Please take note that although we may have chosen to employ a different operation, we utilized addition (+) in this example.

For instance, the code below demonstrates how to multiply the values in each row by specific amounts.

multiply values in each row by a certain amount

```sweep(mat, 1, c(2, 2, 2, 2, 2), "*")
[,1] [,2] [,3]
[1,]    2   12   22
[2,]    4   14   24
[3,]    6   16   26
[4,]    8   18   28
[5,]   10   20   30```

### Example 2: Perform an operation on columns by using sweep()

The sweep() function can be used to increase the values in each column of the matrix by a certain amount as demonstrated by the following code.

Fill in specific figures in each column

```sweep(mat, 2, c(1, 1, 1), "+")
[,1] [,2] [,3]
[1,]    2    7   12
[2,]    3    8   13
[3,]    4    9   14
[4,]    5   10   15
[5,]    6   11   16```

The sweep() method is inferred as follows in this case.

1 was added to each value in the first column.

1 was added to each value in the second column.

1 was added to each value in the third column.

If you are interested to learn more about data science, you can find more articles here finnstats.

The post How to Use the sweep Function in R? appeared first on finnstats.