【问题标题】:Assign value matrix based on index condition根据索引条件分配值矩阵
【发布时间】:2019-03-06 21:38:02
【问题描述】:

如何将值分配到基于向量条件索引矩阵。一个工作示例是:

# Input: 
r <- c(2, 1, 3)
m <- matrix(rep(0, 9), nrow = 3)

# Desired output
result <- matrix(c(0, 1, 0,
               1, 0, 0,
               0, 1, 0), nrow = 3)
result.

# I try with this notation but it does not work:
sapply(1:3, function(x)m[x, r[x]] <- 1)

【问题讨论】:

  • 这不起作用的原因是你在一个函数中进行赋值,所以改变发生在函数的环境中,它与全局环境是分开的

标签: r function matrix indexing apply


【解决方案1】:

我们使用row/column 索引来分配

m[cbind(seq_len(nrow(m)), r)]  <- 1

或使用replace

replace(m, cbind(seq_len(nrow(m)), r), 1)

【讨论】:

    猜你喜欢
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多