Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

r - How to select entire matrix except certain rows and columns?

I have a 5x4 matrix and I want to select all elements (to be set to 0) except those in rows 2 to 4 AND columns 2 to 3. Basically, all the elements along the "edges" of the matrix should be set to 0. Currently, my code is

mat[ -(2:4), -(2:3) ] <- 0

However, this (de)selects the elements in an OR fashion so instead, only the corners of the matrix are set to 0. How can I choose them in AND fashion?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use functions row and col together with logical operations. The following works because R's matrices are in column-first order.

mat <- matrix(seq.int(5*4), nrow = 5)
mat[ !(row(mat) %in% 2:4) | !(col(mat) %in% 2:3) ] <- 0
mat
#     [,1] [,2] [,3] [,4]
#[1,]    0    0    0    0
#[2,]    0    7   12    0
#[3,]    0    8   13    0
#[4,]    0    9   14    0
#[5,]    0    0    0    0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...