如何在R中的列表元素上执行数学运算?
一个列表可以包含许多元素,并且每个元素可以具有不同的类型,但是如果它们是数字元素,那么我们可以对它们执行一些数学运算,例如加,乘,减,除等。为此,我们可以使用Reduce函数通过将数学运算和列表名称提到为Reduce(“ Mathematical_Operation”,List_name)。
示例
x1 <-list(Maths=c(14,28,16,17,19,29),Stats=c(18,19,21,22,28,23))x1
输出结果
$Maths[1] 14 28 16 17 19 29
$Stats
[1] 18 19 21 22 28 23
示例
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
让我们看一下另一个示例,其中list包含矩阵-
x2 <-list(M1=matrix(1:25,nrow=5),M2=matrix(1:25,5))x2
输出结果
$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
以上是 如何在R中的列表元素上执行数学运算? 的全部内容, 来源链接: utcz.com/z/322328.html