【发布时间】:2016-11-01 14:50:35
【问题描述】:
我有一个函数可以找到当前行号之前的最大值。
dt<- setDT(copy(mtcars),keep.rownames = TRUE)
apply(as.matrix(dt$rn), 1, function(x) {
index = as.numeric(ifelse(match(x, dt$rn) == 1, 2, match(x, dt$rn)))
max(dt[1:index-1,"mpg",with = FALSE])
})
# [1] 21.0 21.0 21.0 22.8 22.8 22.8 22.8 22.8 24.4 24.4 24.4 24.4 24.4 24.4 24.4 24.4 24.4 24.4 32.4 32.4 33.9 33.9 33.9 33.9 33.9 33.9 33.9 33.9 33.9 33.9 33.9
# [32] 33.9
但是,我想根据特定组重复相同的操作,例如“齿轮”。我将如何修改代码。我觉得它与这样的事情有关。
dt[,max:=lapply(.SD,function(x){
index = as.numeric(ifelse(match(x,dt$rn) == 1, 2, match(x, dt$rn)))
return(max(dt[1:index-1,"mpg",with = FALSE]))
}),by = gear,.SDcols = "rn"]
我觉得我可能错过了什么..
【问题讨论】:
-
您的函数可以只替换为
cummax(dt$mpg) -
@DavidArenburg op 缺少
1:index-1中的括号,对吧?所以修复这让我在一个值上有所不同 -
@rawr 是的,我认为你是对的
-
dt$mpg是否有组内的值? -
@DavidArenburg 此外,这不仅仅是组内的最大值。但直到该组中的当前行号,因此 1:index-1
标签: r data.table apply