2015-11-06 31 views
0

替換x和接下來的2個值I有一個這樣的輸入:R:如果x =條件,通過X-1的平均值,且x + 3

input=c(8,-200,4,0,9,5,-900,10,8,8)

,我想執行以下操作:

如果輸入<(-100) 之前和值後的值的平均值代替輸入和接下來的兩個值代替

這樣的結果應該是這樣的:

result=c(8,8.5,8.5,8.5,9,5,6.5,6.5,6.5,8) 

df=data.frame(input, result) 

我想這只是工作,如果我只有一個情況下,我的DF如下:

ind <- which(df$input<(-100)) 
df$input[ind:ind+2] <- sapply(ind, function(i) with(df, mean(c(input[i-1], input[i+3])))) 

對於一個以上的情況下,我得到的錯誤信息:

Warning messages: 
1: In ind:ind : numerical expression has 2 elements: only the first used 
2: In ind:ind : numerical expression has 2 elements: only the first used 
3: In df$input[ind:ind + 2] <- sapply(ind, function(i) with(df, mean(c(input[i - : 
    number of items to replace is not a multiple of replacement length 

我也可以有值x + 3是另一個要被替換的值的情況:

input2=c(1,1,2,-100,7,0,-200,4,5,6) 

在這種情況下,我想再次跳過值,並採取下一個x + 3的值(此處爲:2的平均和6),以使得:

result2=c(1,1,2,4,4,4,4,4,4,6) 

任何幫助,將不勝感激。 謝謝!

+0

如果你的條件是'輸入<-100'然後在'input2'只有一個值來代替,因爲'-100'不匹配的情況。 – jlesuffleur

回答

2

這裏是一個解決方案:

myfun <- function(input){ 

    # Replace values by NA 
    ind <- which(input < -100) 
    ind <- unique(c(ind, ind+1, ind+2)) 
    ind <- ind[ind<=length(input)] 
    input[ind] <- NA 

    # Replace NA by mean 
    input[ind] <- rowMeans(cbind(na.locf(input, fromLast = T, na.rm = F), 
           na.locf(input, fromLast = F, na.rm = F)), 
         na.rm = T)[ind] 

    input 
} 

myfun(c(8,8.5,8.5,8.5,9,5,6.5,6.5,6.5,8)) 
# [1] 8.0 8.5 8.5 8.5 9.0 5.0 6.5 6.5 6.5 8.0 
myfun(c(1,1,2,-200,7,0,-200,4,5,6)) 
# [1] 1 1 2 4 4 4 4 4 4 6