将任何函数应用于从 r 中的 which.max 函数返回的元素

apply any function to elements which returned from which.max function in r

我想将任何函数应用于我用 which.max 函数找到其位置的元素。例如,我的示例数据如下:

 $Apr
$Apr$`04-2036`
         date value
92 04-01-2036  0.00
93 04-02-2036  3.13
94 04-03-2036 20.64

$Apr$`04-2037`
          date value
457 04-01-2037  5.32
458 04-02-2037 82.47
459 04-03-2037 15.56


$Dec
$Dec$`04-2039`
           date value
1431 12-01-2039     3
1432 12-02-2039     0
1433 12-03-2039    11

$Dec$`04-2064`
            date value
10563 12-01-2064     0
10564 12-02-2064     5
10565 12-03-2064     0





data<-structure(list(Apr = structure(list(`04-2036` = structure(list(
    date = c("04-01-2036", "04-02-2036", "04-03-2036"), value = c(0, 
    3.13, 20.64)), .Names = c("date", "value"), row.names = 92:94, class = "data.frame"), 
    `04-2037` = structure(list(date = c("04-01-2037", "04-02-2037", 
    "04-03-2037"), value = c(5.32, 82.47, 15.56)), .Names = c("date", 
    "value"), row.names = 457:459, class = "data.frame")), .Names = c("04-2036", 
"04-2037")), Dec = structure(list(`04-2039` = structure(list(
    date = c("12-01-2039", "12-02-2039", "12-03-2039"), value = c(3, 
    0, 11)), .Names = c("date", "value"), row.names = 1431:1433, class = "data.frame"), 
    `04-2064` = structure(list(date = c("12-01-2064", "12-02-2064", 
    "12-03-2064"), value = c(0, 5, 0)), .Names = c("date", "value"
    ), row.names = 10563:10565, class = "data.frame")), .Names = c("04-2039", 
"04-2064"))), .Names = c("Apr", "Dec"))

我已经使用以下函数找到列表列表中每个元素的最大值位置。

drop<-function(y){
  lapply(y, function(x)(x[!(names(x) %in% c("date"))]))
}

q1<-lapply(data, drop)
q2<-lapply(q1, function(x) unlist(x,recursive = FALSE))
daily_max<-lapply(q2, function(x) lapply(x, max))
dailymax <- data.frame(matrix(unlist(daily_max), nrow=length(daily_max), byrow=TRUE))
row.names(dailymax)<-names(daily_max)
apply(dailymax, 1, which.max)

最大的位置。每个元素的值计算如下所示;

Apr Dec 
  2   1 

现在,我想为我的所有数据自动对这些元素应用任何函数(它是 Apr 2 = Apr$04-2037 和 Dec$2039)。

您可以子集化并仅保留每个列表中的最大值数据。

max_value <- apply(dailymax, 1, which.max)
Map(`[[`, data, max_value)

#$Apr
#          date value
#457 04-01-2037  5.32
#458 04-02-2037 82.47
#459 04-03-2037 15.56

#$Dec
#           date value
#1431 12-01-2039     3
#1432 12-02-2039     0
#1433 12-03-2039    11

假设您要将函数 fn 应用到此列表。

fn <- function(x) {x$value <- x$value * 2;x}

您可以将 Map 函数更改为 -

Map(function(x, y) fn(x[[y]]), data, max_value)

#$Apr
#          date  value
#457 04-01-2037  10.64
#458 04-02-2037 164.94
#459 04-03-2037  31.12

#$Dec
#           date value
#1431 12-01-2039     6
#1432 12-02-2039     0
#1433 12-03-2039    22