我想创建一个列"Y",它给出R中每行中特定列"X"的下三行的最大值.
例如-
X Y 1 4 (4=max(2,3,4)) 2 7 (7= max(3,4,7)) 3 9 (9=max(4,7,9)) 4 7 9 2 4
有人能帮忙吗?
鉴于:
x <- c(1, 2, 3, 4, 7, 9, 2, 4)
你可以看一下这个embed
功能:
embed(x, 3) # [,1] [,2] [,3] # [1,] 3 2 1 # [2,] 4 3 2 # [3,] 7 4 3 # [4,] 9 7 4 # [5,] 2 9 7 # [6,] 4 2 9
请注意,这不是正确的长度,我们对第一行不感兴趣,所以让我们做一个修改:
embed(c(x[-1], 0, 0, 0), 3) # [,1] [,2] [,3] # [1,] 4 3 2 # [2,] 7 4 3 # [3,] 9 7 4 # [4,] 2 9 7 # [5,] 4 2 9 # [6,] 0 4 2 # [7,] 0 0 4 # [8,] 0 0 0
从那里,它应该是一个简单的:
apply(embed(c(x[-1], 0, 0, 0), 3), 1, max) # [1] 4 7 9 9 9 4 4 0
为方便起见,作为一个功能:
this_by_n <- function(invec, n = 3, pad_val = NA, FUN = sum) { FUN <- match.fun(FUN) apply(embed(c(invec[-1], rep(pad_val, n)), n), 1, { function(x) if (all(is.na(x))) NA else FUN(x[!is.na(x)]) }) }
试试看:
this_by_n(x, 3, NA, mean) this_by_n(x, 2, NA, max) this_by_n(x, 4, NA, min)