问题描述
不确定这是否符合 R-Inferno 中的条目,但有人可以评论以下替换工作方式背后的逻辑吗?
Not sure this qualifies for an entry in the R-Inferno, but can someone comment on the logic behind the way the following replacement works?
foo<-matrix(1:6,2)
bar<-foo[2,c(1,3,1)]
bar
# [1] 2 6 2
foo[2,c(1,3,1)]<-foo[2,c(1,3,1)]+5
foo
# [,1] [,2] [,3]
# [1,] 1 3 5
# [2,] 7 4 11
我的问题是:在生成bar
时,重复的坐标导致输出中有重复的元素,但是修改foo
时,重复的坐标没有 导致重复的加法运算.(相比之下, for(j in c(1,3,1) ) foo[2,j]<-foo[2,j]+5
确实如此).为什么&[<-
究竟是如何忽略重复索引的?
My question is: when generating bar
, the repeated coordinate results in a repeated element in the output, but when modifying foo
, the repeated coordinate does not result in a repeated addition operation. (By comparison, for(j in c(1,3,1) ) foo[2,j]<-foo[2,j]+5
does). Why & how exactly does [<-
essentially ignore the repeated index?
推荐答案
From help("[<-")
:
子赋值是按顺序完成的,所以如果指定一个索引更多将导致索引的最新分配值不止一次.
foo<-matrix(1:6,2)
foo[1,rep(1,2)] <- c(1,42)
# [,1] [,2] [,3]
#[1,] 42 3 5
#[2,] 2 4 6
这篇关于分配给具有重复索引的矩阵的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!