How to remove row that contains maximum for each column in R data frame?

R ProgrammingServer Side ProgrammingProgramming

To remove row that contains maximum for each column in R data frame, we can follow the below steps −

  • First of all, create a data frame.
  • Then, remove the rows having maximum for each column using lapply and which.max function.

Create the data frame

Let's create a data frame as shown below −

 Live Demo

> x1<-rpois(20,5)
> x2<-rpois(20,9)
> df<-data.frame(x1,x2)
> df

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

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

Remove rows with maximum for each column

Using lapply and which.max function to remove rows having maximum for each column in df −

 Live Demo

> x1<-rpois(20,5)
> x2<-rpois(20,9)
> df<-data.frame(x1,x2)
> as.data.frame(lapply(df, function(x) x[-which.max(x)]))

Output

   x1 x2
1  1  10
2  8  9
3  7  9
4  4  6
5  4 10
6  8  7
7  5  8
8  4  8
9  4 13
10 4 10
11 3 10
12 7  7
13 4  7
14 3  4
15 5  8
16 5 11
17 6 10
18 4  7
19 6  6
raja
Published on 02-Aug-2021 13:22:44
Advertisements