R中按行编号非零元素

时间:2019-04-12 21:13:07

标签: r matrix

我希望按行编号matrix中的非零元素。这是一个小的数据集和所需的结果。我希望在基础R中使用一个解决方案。

my.data <- matrix(c(10,  0,  0,  0,  0,
                     0,  3,  9,  0,  1,
                     2, 12,  0,  0,  0,
                     5,  5,  5,  0,  5,
                     0,  0,  0,  0,  0), nrow = 5, byrow = TRUE)

desired.result <- matrix(c( 1,  0,  0,  0,  0,
                            0,  1,  2,  0,  3,
                            1,  2,  0,  0,  0,
                            1,  2,  3,  0,  4,
                            0,  0,  0,  0,  0), nrow = 5, byrow = TRUE)

2 个答案:

答案 0 :(得分:7)

另外两个选项:

# create new matrix with multiplication
t(apply(my.data != 0, 1, cumsum)) * (my.data != 0)


# alternative:
# replace elements in original matrix
my.data[my.data != 0] = t(apply(my.data != 0, 1, cumsum))[my.data != 0]
my.data
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    0    0    0    0
# [2,]    0    1    2    0    3
# [3,]    1    2    0    0    0
# [4,]    1    2    3    0    4
# [5,]    0    0    0    0    0

答案 1 :(得分:4)

这是一个相对幼稚的基础R方法:

t(apply(my.data, 1, function(x) {
    x[x != 0] <- seq_len(sum(x != 0))
    x
    }))

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