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
117 views
in Technique[技术] by (71.8m points)

r - How to delete specific rows and columns from a matrix in a smarter way?

Let's say t1 is :

t1 <- array(1:20, dim=c(10,10))

      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    1   11    1   11    1   11    1   11    1    11
 [2,]    2   12    2   12    2   12    2   12    2    12
 [3,]    3   13    3   13    3   13    3   13    3    13
 [4,]    4   14    4   14    4   14    4   14    4    14
 [5,]    5   15    5   15    5   15    5   15    5    15
 [6,]    6   16    6   16    6   16    6   16    6    16
 [7,]    7   17    7   17    7   17    7   17    7    17
 [8,]    8   18    8   18    8   18    8   18    8    18
 [9,]    9   19    9   19    9   19    9   19    9    19
[10,]   10   20   10   20   10   20   10   20   10    20

I want to delete row 4-6 and column 7-9 from this matrix.

I know how to remove it one by one using

t2 <- t1[,-7]
t3 <- t2[,-8]
t4 <- t3[,-9]
t5 <- t4[-4,]
t6 <- t5[-5,]
t7 <- t6[-6,]

However, I believe it is the most stupid way of doing it. Could you mind to advice some smarter ways of doing it?

question from:https://stackoverflow.com/questions/12919984/how-to-delete-specific-rows-and-columns-from-a-matrix-in-a-smarter-way

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

1 Reply

0 votes
by (71.8m points)

You can do:

t1<- t1[-4:-6,-7:-9]

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

...