How to remove rows in an R data frame using row names?

R ProgrammingServer Side ProgrammingProgramming

There are a lot of ways to subset an R data frame and sometimes we need to do it by removing rows. In general, the rows are removed by using the row index number but we can do the same by using row names as well. This can be done by storing the row names that should be removed in a vector and then removing through subsetting with single square brackets as shown in the below examples.

Example

Consider the below data frame:

> x<-rnorm(20,1,0.04)
> y<-rnorm(20,100,4)
> row.names(df)<-LETTERS[1:20]
> df

Output

      x        y
A 0.9454799 96.62077
B 0.9642909 101.54903
C 1.0294169 97.17593
D 0.9877072 98.98962
E 1.0182932 92.32761
F 1.0351041 103.04182
G 0.9613700 90.65195
H 1.0240703 99.63975
I 0.9424871 97.11730
J 0.9876748 108.07684
K 1.0652311 102.14823
L 1.0196251 93.51378
M 0.9752639 100.57394
N 0.9890722 101.37151
O 0.9873279 100.37910
P 0.9564027 96.94806
Q 0.9456446 103.40934
R 0.9617322 94.89198
S 0.9956141 86.43256
T 1.0253881 101.52844

Making vector of row names that needs to be removed:

Example

> row_names_df_to_remove<-c("A","B","C","D","E")

Removing the specified row names:

Example

> df[!(row.names(df) %in% row_names_df_to_remove),]

Output

       x         y
F 1.0351041 103.04182
G 0.9613700 90.65195
H 1.0240703 99.63975
I 0.9424871 97.11730
J 0.9876748 108.07684
K 1.0652311 102.14823
L 1.0196251 93.51378
M 0.9752639 100.57394
N 0.9890722 101.37151
O 0.9873279 100.37910
P 0.9564027 96.94806
Q 0.9456446 103.40934
R 0.9617322 94.89198
S 0.9956141 86.43256
T 1.0253881 101.52844

Let’s have a look at another example:

Example

Live Demo

> set.seed(3247)
> x1<-rpois(20,1)
> x2<-rpois(20,5)
> df1<-data.frame(x1,x2)
> df1

Output

x1 x2
1 3 5
2 1 8
3 3 3
4 0 6
5 2 2
6 1 6
7 0 1
8 2 2
9 1 3
10 0 4
11 3 1
12 0 4
13 0 5
14 1 4
15 1 3
16 1 7
17 2 3
18 0 0
19 1 3
20 0 5

Example

> row.names.df1<-c(1:5)
> df1[!(row.names(df1) %in% row.names.df1),]

Output

x1 x2
6 1 6
7 0 1
8 2 2
9 1 3
10 0 4
11 3 1
12 0 4
13 0 5
14 1 4
15 1 3
16 1 7
17 2 3
18 0 0
19 1 3
20 0 5
raja
Published on 23-Nov-2020 09:34:57
Advertisements