1

我想将 0 和 1 的矩阵转换为相应的矩阵,该矩阵给出非零条目的累积行总和。示例输入和输出如下所示:

set.seed(404)
input  <- matrix(rbinom(10 * 5, 1, 0.5), ncol = 5, nrow = 5)
output <- data.frame(a = c(1, 1, 1, 1, 0),
                     b = c(0, 0, 0, 0, 0),
                     c = c(2, 2, 0, 2, 1),
                     d = c(3, 0, 0, 3, 2),
                     e = c(0, 3, 0, 0, 0))

input
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    1    0    1    1    0
#[2,]    1    0    1    0    1
#[3,]    1    0    0    0    0
#[4,]    1    0    1    1    0
#[5,]    0    0    1    1    0
output
#  a b c d e
#1 1 0 2 3 0
#2 1 0 2 0 3
#3 1 0 0 0 0
#4 1 0 2 3 0
#5 0 0 1 2 0
4

1 回答 1

4

我们可以使用applywithMARGIN=1来获取cumsum“输入”的每一行,转置 ( t) 并与“输入”相乘,以便 1 值被cumsum输出替换,“0”保持不变。

input*t(apply(input, 1, cumsum))
#   [,1] [,2] [,3] [,4] [,5]
#[1,]    1    0    2    3    0
#[2,]    1    0    2    0    3
#[3,]    1    0    0    0    0
#[4,]    1    0    2    3    0
#[5,]    0    0    1    2    0

或者我们可以使用rowCumsumsfromlibrary(matrixStats)来获取cumsum每一行的值并像以前一样相乘。

library(matrixStats)
input*rowCumsums(input)
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    1    0    2    3    0
#[2,]    1    0    2    0    3
#[3,]    1    0    0    0    0
#[4,]    1    0    2    3    0
#[5,]    0    0    1    2    0
于 2015-08-27T15:10:12.433 回答