Reputation: 369
I have a list that contains vectors of length 2, the first element of the vector denotes one data type, and the second - the second data type
[[1]]
[1] "51224.99" "0.879"
[[2]]
[1] "51224.50" "0.038"
[[3]]
[1] "51224.00" "0.038"
[[4]]
[1] "51223.50" "0.038"
[[5]]
[1] "51223.00" "0.062"
[[6]]
[1] "51222.50" "0.038"
[[7]]
[1] "51222.00" "0.038"
[[8]]
[1] "51221.86" "0.370"
[[9]]
[1] "51221.82" "0.015"
[[10]]
[1] "51221.50" "0.038"
[[11]]
[1] "51221.44" "2.100"
[[12]]
[1] "51221.39" "0.196"
[[13]]
[1] "51221.00" "0.038"
[[14]]
[1] "51220.50" "0.038"
[[15]]
[1] "51220.19" "0.292"
[[16]]
[1] "51220.00" "0.038"
[[17]]
[1] "51219.97" "0.012"
[[18]]
[1] "51219.62" "0.684"
[[19]]
[1] "51219.50" "0.038"
[[20]]
[1] "51219.02" "2.311"
I need to find the maximum value by the second element of the vector. That is, in the end result, I should get the following result:
[1] "51219.02" "2.311"
since the maximum second number in vectors is 2.311
Upvotes: 0
Views: 902
Reputation: 887851
Here is an option with rbind
, extract the second column, convert to numeric, find the max index to subset the list
lst1[which.max(as.numeric(do.call(rbind, lst1)[,2]))]
Upvotes: 0
Reputation: 162
You could just turn it into a dataframe! Here's how I would do it:
(first I make an example list to mimic yours):
ex <- purrr::map(seq(12), function(i) c(rnorm(1), rnorm(1)))
Then you can use purrr to turn it into a dataframe, and filter to filter to where the second value is the max of that column:
purrr::map_df(ex, function(x) data.frame(val1 = x[1], val2 = x[2])) %>%
dplyr::filter(val2 == max(val2))
You should be able to use this example^ by replacing ex
with the name of your list.
Upvotes: 1
Reputation: 1810
Assuming your list is called yourList
, you can do the follwoing:
secondValuesNumeric <- as.numeric(sapply(yourList,"[[",2))
maxIndex <- which.max(secondValuesNumeric)
result <- yourList[[maxIndex]]
Upvotes: 2