Deleting a conditional row in data frame R

Here is an example data frame:

df <- data.frame(t1 = c(1,2,3,4), t2 = c(7,3,8,1), t3 = c(1,1,1,1)) df t1 t2 t3 1 1 7 1 2 2 3 1 3 3 8 1 4 4 1 1 

My goal is to remove the maximum value from each column. However, for columns of type t3, where all values โ€‹โ€‹in the column are equal, I simply delete one value so that all three columns in the data frame end with three rows, as shown below:

 df2 t1 t2 t3 1 1 7 1 2 2 3 1 3 3 1 1 
+5
source share
2 answers

How about using which.max , since it will select only one value (i.e. the index of the first occurrence of the maximum value):

 as.data.frame(lapply(df, function(x) x[-which.max(x)])) # t1 t2 t3 # 1 1 7 1 # 2 2 3 1 # 3 3 1 1 
+4
source

Try

 library(data.table) setDT(df)[, lapply(.SD, function(x) x[-which.max(x)])] 
+4
source

All Articles