簡體   English   中英

在R中寫一個function,從數據幀列表中提取每個數據幀中某個變量的最大值

[英]Write a function in R to extract the highest value of a variable in each data frame from 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)

我想寫一個 function 從兩個數據幀返回價格的最大值及其對應的日期。

在基礎 R 中,我們可以使用lapply -

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

或使用dplyrpurrr -

library(dplyr)
library(purrr)

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM