【问题标题】:Construct matrix with columns of data and zeros, without using for-loop构造具有数据列和零列的矩阵,而不使用 for 循环
【发布时间】:2016-11-15 20:26:52
【问题描述】:

我有一个数字数据矩阵,其中包含讨厌的零列,我想删除这些数据以进行一些数据处理。我使用is_zero_column <- colSums(matrix) == 0 跟踪哪些列是零列,并通过matrix <- matrix[,colSums(matrix)!=0] 删除零列

现在我将如何做相反的事情,我使用我的 TRUE/FALSE 的is_zero_column(如果为零列则为 TRUE)将零列重新插入到我的矩阵中?

如果这不是 R,我会使用 forloop 来构造一个新矩阵:(在 python-ish 伪代码中)

new_matrix;
for i in is_zero_column:
  if i is TRUE:
    new_matrix <- new_matrix.append_column(rep(0, columnlength))
  else:
    new_matrix <- new_matrix.append_column(matrix[,1])
    matrix <- matrix[,-1]
return new_matrix;

但是,这是 R,所以试图找到一种非 for 循环的方式来做到这一点。

【问题讨论】:

    标签: r matrix


    【解决方案1】:

    如果Q 是没有零列的矩阵:

    Q
    #     [,1] [,2]
    #[1,]    1    0
    #[2,]    0    0
    #[3,]    0    1
    

    is_zero_column如下:

    is_zero_column = c(F,T,F)
    

    您可以创建一个零矩阵,其行数等于 Q 中的行数,列数等于 is_zero_column 向量的长度,然后使用 Q 中的值更新非零列值:

    Q1 = matrix(0, nrow(Q), length(is_zero_column))
    Q1[, !is_zero_column] = Q
    Q1
    #     [,1] [,2] [,3]
    #[1,]    1    0    0
    #[2,]    0    0    0
    #[3,]    0    0    1
    

    【讨论】:

    • 太好了,谢谢!!如果您愿意分享任何见解,请告诉我。似乎在 R 中,您从数据结构的形式开始,然后找到选择和修改行/列以符合您的逻辑的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-08
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多