簡體   English   中英

將數字添加到數據框中的一系列行 (R)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM