我有一个矢量, v和一个间隔矢量, w 。 我想在每个区间中找到函数的最大值f(x) 。 有没有比跟踪代码更快的方法来查找结果? 例如:
v = c(3.5, 2.5, 4, 6.5, 10, 2.3, 1.8, 4.7, 12, 11.5) w = c(0, 5, 15, 20) f = function(x){x^2} > max = unlist(list(sapply(split(v, cut(v, w),drop = TRUE), function(v) v[which.max(f(v))])), use.names = FALSE) > max [1] 4.7 12.0I have a vector, v, and a vector of intervals, w. I want to find the maximum value of a function, f(x), in each interval. Is there a faster way than following code for finding the result? For example:
v = c(3.5, 2.5, 4, 6.5, 10, 2.3, 1.8, 4.7, 12, 11.5) w = c(0, 5, 15, 20) f = function(x){x^2} > max = unlist(list(sapply(split(v, cut(v, w),drop = TRUE), function(v) v[which.max(f(v))])), use.names = FALSE) > max [1] 4.7 12.0最满意答案
那么findInterval和tapply 。 findInterval就像cut ,但没有转换为因子的开销
tapply(v,findInterval(v,w),function(x)x[which.max(f(x))]) # 1 2 # 4.7 12.0或者如果你想要最大值
tapply(f(v),findInterval(v,w),max) # 1 2 # 22.09 144.00或者你可以使用这样一个事实,即你的函数对于所有正值都是单调递增的。
f(tapply(v,findInterval(v,w),max))请注意,您需要指定边界处发生的情况(阅读帮助文件)
library(microbenchmark) microbenchmark( mnel = tapply(v,findInterval(v,w),max), flodel = unname(vapply(split(f(v), cut(v, w), drop = TRUE), max, numeric(1L))), flodel2 = unname(vapply(split(seq_along(v), findInterval(v, w)), function(i, v, fv)v[i][which.max(fv[i])], numeric(1L), v, f(v)))) # Unit: microseconds # expr min lq median uq max neval # mnel 260.945 262.9155 264.2265 276.0645 458.670 100 # flodel 331.218 334.3585 336.0580 351.1985 694.715 100 #flodel2 124.998 127.3230 128.5170 137.0505 354.545 100What about findInterval and tapply. findInterval is like cut, but without the overhead of converting to factors
tapply(v,findInterval(v,w),function(x)x[which.max(f(x))]) # 1 2 # 4.7 12.0Or if you want the maximum value
tapply(f(v),findInterval(v,w),max) # 1 2 # 22.09 144.00Or you could use the fact that your function is monotonically increasing for all positive values and do.
f(tapply(v,findInterval(v,w),max))Note that you will need to specify what happens at the boundaries (read the help file)
library(microbenchmark) microbenchmark( mnel = tapply(v,findInterval(v,w),max), flodel = unname(vapply(split(f(v), cut(v, w), drop = TRUE), max, numeric(1L))), flodel2 = unname(vapply(split(seq_along(v), findInterval(v, w)), function(i, v, fv)v[i][which.max(fv[i])], numeric(1L), v, f(v)))) # Unit: microseconds # expr min lq median uq max neval # mnel 260.945 262.9155 264.2265 276.0645 458.670 100 # flodel 331.218 334.3585 336.0580 351.1985 694.715 100 #flodel2 124.998 127.3230 128.5170 137.0505 354.545 100更多推荐
发布评论