在R中:如何将符合特定条件的值设置为特定值

时间:2015-06-05 08:47:12

标签: r

假设我在R中有以下矩阵 - 我如何优雅地将所有小于0的值设置为零(例如)

      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    0    1    3    5    9   11   15   17   21    27
 [2,]   -1    0    2    4    8   10   14   16   20    26
 [3,]   -3   -2    0    2    6    8   12   14   18    24
 [4,]   -5   -4   -2    0    4    6   10   12   16    22
 [5,]   -9   -8   -6   -4    0    2    6    8   12    18
 [6,]  -11  -10   -8   -6   -2    0    4    6   10    16
 [7,]  -15  -14  -12  -10   -6   -4    0    2    6    12
 [8,]  -17  -16  -14  -12   -8   -6   -2    0    4    10
 [9,]  -21  -20  -18  -16  -12  -10   -6   -4    0     6
[10,]  -27  -26  -24  -22  -18  -16  -12  -10   -6     0

2 个答案:

答案 0 :(得分:1)

尝试

m1[m1<0] <- 0

m1 <- (m1 >=0)*m1

答案 1 :(得分:1)

ifelse() - 方法

# some data
m <- matrix((1:10)-5, ncol=5)

##      [,1] [,2] [,3] [,4] [,5]
## [1,]   -4   -2    0    2    4
## [2,]   -3   -1    1    3    5

# setting values below zero to zero
ifelse(m < 0, 0, m )

##      [,1] [,2] [,3] [,4] [,5]
## [1,]    0    0    0    2    4
## [2,]    0    0    1    3    5