Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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?

like image 508
psiu Avatar asked Oct 16 '12 17:10

psiu


People also ask

How do you delete rows and columns in a matrix?

The easiest way to remove a row or column from a matrix is to set that row or column equal to a pair of empty square brackets [] . For example, create a 4-by-4 matrix and remove the second row. Now remove the third column.

How do I delete specific rows?

Right-click in a table cell, row, or column you want to delete. On the menu, click Delete Cells. To delete one cell, choose Shift cells left or Shift cells up. To delete the row, click Delete entire row.

How do I remove rows and columns from a matrix in R?

To remove the row(s) and column(s) of a current matrix in R, we use the c() function.

How do I remove a row based on a condition in R?

For example, we can use the subset() function if we want to drop a row based on a condition. If we prefer to work with the Tidyverse package, we can use the filter() function to remove (or select) rows based on values in a column (conditionally, that is, and the same as using subset).


1 Answers

You can do:

t1<- t1[-4:-6,-7:-9] 
like image 80
tcash21 Avatar answered Sep 21 '22 03:09

tcash21