如何将R中矩阵的负值转换为0?
要将矩阵中的负值转换为0,我们可以使用pmax函数。例如,如果我们有一个名为M的矩阵,其中包含一些负值、正值和零值,则可以通过使用命令pmax(M,0)将M中的负值转换为0。
示例
考虑以下数据框 -
M1<-matrix(sample(-10:2,40,replace=TRUE),ncol=2) M1
输出
[,1] [,2] [1,] 0 -2 [2,] -1 0 [3,] -10 1 [4,] -4 -8 [5,] -7 -8 [6,] 0 0 [7,] -7 0 [8,] -8 -3 [9,] -1 -9 [10,] -4 -10 [11,] 1 -7 [12,] 0 -5 [13,] -6 -3 [14,] -4 -4 [15,] -4 -4 [16,] 0 2 [17,] -7 -2 [18,] -7 -2 [19,] -5 -5 [20,] -6 -7
将矩阵M1中的负值转换为0 -
示例
pmax(M1,0)
输出
[,1] [,2] [1,] 0 0 [2,] 0 0 [3,] 0 1 [4,] 0 0 [5,] 0 0 [6,] 0 0 [7,] 0 0 [8,] 0 0 [9,] 0 0 [10,] 0 0 [11,] 1 0 [12,] 0 0 [13,] 0 0 [14,] 0 0 [15,] 0 0 [16,] 0 2 [17,] 0 0 [18,] 0 0 [19,] 0 0 [20,] 0 0
示例
M2<-matrix(sample(-10:10,80,replace=TRUE),ncol=4) M2
输出
[,1] [,2] [,3] [,4] [1,] -10 1 4 7 [2,] -9 5 6 2 [3,] 7 4 1 -5 [4,] 2 9 0 2 [5,] -2 -6 1 -9 [6,] 8 -9 -9 1 [7,] 3 -3 0 -1 [8,] 5 0 -3 5 [9,] -2 5 7 -5 [10,] -3 0 -8 1 [11,] -4 3 -2 -4 [12,] 5 4 -5 2 [13,] 0 10 -1 -8 [14,] 5 -9 -4 -1 [15,] 6 -6 2 0 [16,] -6 -9 -5 -8 [17,] -4 4 -9 -3 [18,] 4 -10 4 7 [19,] -9 -8 2 -4 [20,] -2 3 9 -8
将矩阵M2中的负值转换为0 -
示例
pmax(M2,0)
输出
[,1] [,2] [,3] [,4] [1,] 0 1 4 7 [2,] 0 5 6 2 [3,] 7 4 1 0 [4,] 2 9 0 2 [5,] 0 0 1 0 [6,] 8 0 0 1 [7,] 3 0 0 0 [8,] 5 0 0 5 [9,] 0 5 7 0 [10,] 0 0 0 1 [11,] 0 3 0 0 [12,] 5 4 0 2 [13,] 0 10 0 0 [14,] 5 0 0 0 [15,] 6 0 2 0 [16,] 0 0 0 0 [17,] 0 4 0 0 [18,] 4 0 4 7 [19,] 0 0 2 0 [20,] 0 3 9 0
广告