【发布时间】: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