[英]Adding a number to a range of rows in a data frame (R)
我有一组数据(累积降水),当仪器重置时,记录的降水起始水平发生变化。 为了纠正这个问题,我需要将值下降到新记录的数量添加到新记录中,以便值不断增加,因为它们应该。
即下面的数字范围将从:26、27、28、18、19、20更改为:26、27、28、28、29、30
通过将 drop (10) 添加到 drop 之后的所有值。
我想我需要通过一系列单元格(12746 到 17567)循环操作
你可以这样做:
# An example like yours, but with multiple drops.
vals = c(26, 27, 28, 18, 19, 20, 15, 17, 19);
correct_drops = function(vals)
{
n = length(vals);
# which() will get you indices where the condition holds true.
# Here it will get you the sites where 2 consecutive values
# have that the first value is greater than the second, meaning a drop.
indices_before_drop = which(vals[1:(n-1)] - vals[2:n] > 0);
# Looping through all drops, correcting each individually.
vals_corrected = vals;
for (ibd in indices_before_drop)
{
iad = ibd + 1;
drop = vals_corrected[ibd] - vals_corrected[iad];
vals_corrected = c(vals_corrected[1:ibd], (vals_corrected[iad:n] + drop));
}
return (vals_corrected);
}
vals_corrected = correct_drops(vals);
当然也有特殊情况需要考虑。
无论如何,我相信which(..)
和c(..)
以及子向量范围v[a:b]
是你的朋友。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.