分配给具有重复索引的矩阵的子集 [英] Assignment to subset of a matrix with repeated indices

查看:29
本文介绍了分配给具有重复索引的矩阵的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定这是否符合 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("[<-"):

子赋值是按顺序完成的,所以如果指定一个索引更多将导致索引的最新分配值不止一次.

Subassignment is done sequentially, so if an index is specified more than once the latest assigned value for an index will result.

foo<-matrix(1:6,2)

foo[1,rep(1,2)] <- c(1,42)

#     [,1] [,2] [,3]
#[1,]   42    3    5
#[2,]    2    4    6

这篇关于分配给具有重复索引的矩阵的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆