gpt4 book ai didi

R:如何按行对矩阵中的对求和?

转载 作者:行者123 更新时间:2023-12-02 06:15:20 25 4
gpt4 key购买 nike

这可能很容易。我有一个矩阵:

testM <- matrix(1:40, ncol = 4, byrow = FALSE)
testM
[,1] [,2] [,3] [,4]
[1,] 1 11 21 31
[2,] 2 12 22 32
[3,] 3 13 23 33
[4,] 4 14 24 34
[5,] 5 15 25 35
[6,] 6 16 26 36
[7,] 7 17 27 37
[8,] 8 18 28 38
[9,] 9 19 29 39
[10,] 10 20 30 40

我想逐行“减少”矩阵求和列对。预期结果:

      [,1] [,2]
[1,] 12 52
[2,] 14 54
[3,] 16 56
[4,] 18 58
[5,] 20 60
[6,] 22 62
[7,] 24 64
[8,] 26 66
[9,] 28 68
[10,] 30 70

我试过了,但是不行

X <- apply(1:(ncol(testM)/2), 1, function(x) sum(testM[x], testM[x+1]) )

Error in apply(1:(ncol(testM)/2), 1, function(x) sum(testM[x], testM[x + :
dim(X) must have a positive length

最佳答案

testM[,c(T,F)]+testM[,c(F,T)];
## [,1] [,2]
## [1,] 12 52
## [2,] 14 54
## [3,] 16 56
## [4,] 18 58
## [5,] 20 60
## [6,] 22 62
## [7,] 24 64
## [8,] 26 66
## [9,] 28 68
## [10,] 30 70

关于R:如何按行对矩阵中的对求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36432686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com