如何在 R 中对列表元素执行数学运算?
列表可以包含很多元素,每个元素的类型可以是不同的,但如果元素是数字,则我们可以对它们执行一些数学运算,例如加法、乘法、减法、除法等。为此,我们可以通过指定数学运算和列表名称作为 Reduce(“Mathematical_Operation”, List_name) 来使用 Reduce 函数。
示例
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
让我们看另一个示例,其中列表包含矩阵 -
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
广告