【发布时间】:2015-11-06 13:58:26
【问题描述】:
我有这样的输入:
input=c(8,-200,4,0,9,5,-900,10,8,8)
我想做以下事情:
如果输入
所以结果应该是这样的:
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)
任何帮助将不胜感激。 谢谢!
【问题讨论】:
-
如果您的条件是
input < -100,那么在input2中只有一个值可以替换,因为-100不符合条件。
标签: r indexing replace mean sapply