# How to perform mathematical operations on elements of a list in R?

R ProgrammingServer Side ProgrammingProgramming

#### Artificial Intelligence : The Future Of Programming

15 Lectures 54 mins

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### C Programming from scratch- Master C Programming

Best Seller

60 Lectures 8 hours

A list can contain many elements and each of them can be of different type but if they are numerical then we can perform some mathematical operations on them such as addition, multiplication, subtraction, division, etc. To do this, we can use Reduce function by mentioning the mathematical operation and the list name as Reduce(“Mathematical_Operation”, List_name).

## Example

x1 <-list(Maths=c(14,28,16,17,19,29),Stats=c(18,19,21,22,28,23))
x1

## Output

$Maths [1] 14 28 16 17 19 29$Stats
[1] 18 19 21 22 28 23

## Example

Reduce("+",x1)
[1] 32 47 37 39 47 52
Reduce("-",x1)
[1] -4 9 -5 -5 -9 6
Reduce("*",x1)
[1] 252 532 336 374 532 667
Reduce("/",x1)
[1] 0.7777778 1.4736842 0.7619048 0.7727273 0.6785714 1.2608696
Reduce("/",x1)/3
[1] 0.2592593 0.4912281 0.2539683 0.2575758 0.2261905 0.4202899
Reduce("+",x1)/2
[1] 16.0 23.5 18.5 19.5 23.5 26.0
Reduce("*",x1)/length(x1)
[1] 126.0 266.0 168.0 187.0 266.0 333.5
Reduce("+",x1)/length(x1)
[1] 16.0 23.5 18.5 19.5 23.5 26.0
Reduce("+",x1)/sqrt(10)
[1] 10.11929 14.86271 11.70043 12.33288 14.86271 16.44384
Reduce("+",x1)/log10(10)
[1] 32 47 37 39 47 52

Lets’ have a look at another example, where list contains matrices −

x2 <-list(M1=matrix(1:25,nrow=5),M2=matrix(1:25,5))
x2

## Output

$M1 [,1] [,2] [,3] [,4] [,5] [1,] 1 6 11 16 21 [2,] 2 7 12 17 22 [3,] 3 8 13 18 23 [4,] 4 9 14 19 24 [5,] 5 10 15 20 25$M2
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
Reduce("+",x2)
[,1] [,2] [,3] [,4] [,5]
[1,] 2 12 22 32 42
[2,] 4 14 24 34 44
[3,] 6 16 26 36 46
[4,] 8 18 28 38 48
[5,] 10 20 30 40 50
Reduce("-",x2)
[,1] [,2] [,3] [,4] [,5]
[1,] 0 0 0 0 0
[2,] 0 0 0 0 0
[3,] 0 0 0 0 0
[4,] 0 0 0 0 0
[5,] 0 0 0 0 0
Reduce("/",x2)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 1 1 1
[2,] 1 1 1 1 1
[3,] 1 1 1 1 1
[4,] 1 1 1 1 1
[5,] 1 1 1 1 1
Reduce("*",x2)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 36 121 256 441
[2,] 4 49 144 289 484
[3,] 9 64 169 324 529
[4,] 16 81 196 361 576
[5,] 25 100 225 400 625
Reduce("+",x2)/length(x2)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
Reduce("+",x2)/2
[,1] [,2] [,3] [,4] [,5]
[1,] 1 6 11 16 21
[2,] 2 7 12 17 22
[3,] 3 8 13 18 23
[4,] 4 9 14 19 24
[5,] 5 10 15 20 25
Reduce("+",x2)/log10(10)
[,1] [,2] [,3] [,4] [,5]
[1,] 2 12 22 32 42
[2,] 4 14 24 34 44
[3,] 6 16 26 36 46
[4,] 8 18 28 38 48
[5,] 10 20 30 40 50
Updated on 24-Aug-2020 12:36:04