Prince Modi
Prince Modi

Reputation: 495

select dataframes from a list based on maximum column value

I have a list x2 having two data frames, x and x1. Both have 4 columns: n,m,l and k. I want to select the data frame that has maximum last value for column k.

In the below example, I would like data frame 2nd to be selected because the last value in column K is greater than last value in column K for data frame 1.

x <- data.frame(n = c(2, 13, 5),m = c(2, 23, 6),l = c(2, 33, 7),k = c(2, 43, 8))
x1 <- data.frame((n = c(2, 3, 15),m = c(2, 3, 16),l = c(2, 3, 17),k = c(2, 3, 18))
x2<-list(x,x1)

Upvotes: 0

Views: 53

Answers (2)

Sathish
Sathish

Reputation: 12703

Using lapply, loop through the list of x2 and get the last value of k column of that data frame. Using which.max, find the index which has the maximum of the previous lapply command and extract that dataframe from x2

Note: This code does not account for ties in the last value of k column.

x2[which.max(lapply(x2, function(x) tail(x$k, 1)))]

# [[1]]
#    n  m  l  k
# 1  2  2  2  2
# 2  3  3  3  3
# 3 15 16 17 18

Upvotes: 1

Michal
Michal

Reputation: 215

if(x$k[length(x$k)] >= x1$k[length(x1$k)]) x else x1

an if statement where x$k[length(x$k)] - gets the last element from column k of matrix x

   n  m  l  k
1  2  2  2  2
2  3  3  3  3
3 15 16 17 18

Upvotes: 1

Related Questions