简体   繁体   中英

Write a function in R to extract the highest value of a variable in each data frame from a list of data frames

I have a list of data frames:

df1 <- data.frame(day = c(1,2,3,4), price = c(100,120,90,22))
df2 <- data.frame(day = c(1,2,3,4,5,6,7), price = c(1,11,20,5,88,25,6))
my_list <- list(df1, df2)

I want to write a function which returns the max value of price and its corresponding day from both data frames.

In base R, we can use lapply -

lapply(my_list, function(x) x[which.max(x$price), ])

Or using dplyr and purrr -

library(dplyr)
library(purrr)

map(my_list, ~.x %>% slice(which.max(price)))

#[[1]]
#  day price
#1   2   120

#[[2]]
#  day price
#1   5    88

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM