簡體   English   中英

R Dplyr; 計算上一行的兩列之間的差異,但將結果放入下一行而不進行for循環

[英]R Dplyr; calculating difference between two columns from previous row but putting result in next row without for loop

我正在嘗試解決以下問題,在該問題中,我希望使用R中的dplyr計算下一行的上一行與上一行之間的差,最好不使用循環。 在此特定示例中,我想從上一行計算r_j-s_j,然后將結果粘貼到下一行。

以下是一些示例數據:

require(tidyverse)
data = tibble(LM = c(100, 300, 400, 500, 600, 700, 800, 1300), s_j = c(2,2,2,1,2,2,1,1)) %>% 
       bind_cols(,r_j = rep(25, nrow(.))

     LM   s_j   r_j
1   100     2    25
2   300     2    25
3   400     2    25
4   500     1    25
5   600     2    25
6   700     2    25
7   800     1    25
8  1300     1    25

我想要的輸出是這個;

     LM   s_j   r_j
1   100     2    25
2   300     2    23
3   400     2    21
4   500     1    19
5   600     2    18
6   700     2    16
7   800     1    14
8  1300     1    13

解決此問題的方法是:

for (k in 2:nrow(data)){ 
   tmp = data$r_j[k-1] - data$s_j[k-1]
   data$r_j[k] = tmp 
}

產生

     LM   s_j   r_j
1   100     2    25
2   300     2    23
3   400     2    21
4   500     1    19
5   600     2    18
6   700     2    16
7   800     1    14
8  1300     1    13

但是肯定有比R中的for循環更好的解決方案嗎? 謝謝你的幫助。

一種方法是生成s_j的累加和,然后從r_j中減去

data %>% mutate(
    temp = cumsum(s_j),
    r_j2 = r_j-temp
)
# A tibble: 8 x 5
     LM   s_j   r_j  temp  r_j2
   <dbl> <dbl> <dbl> <dbl> <dbl>
1   100     2    25     2    23
2   300     2    25     4    21
3   400     2    25     6    19
4   500     1    25     7    18
5   600     2    25     9    16
6   700     2    25    11    14
7   800     1    25    12    13
8  1300     1    25    13    12

編輯:要生成所需的確切輸出,可以從其總和中減去s_j的值,並得到以下結果:

data %>% mutate(
     temp = cumsum(s_j)-s_j,
     r_j2 = r_j-temp
 )
# A tibble: 8 x 5
     LM   s_j   r_j  temp  r_j2
  <dbl> <dbl> <dbl> <dbl> <dbl>
1   100     2    25     0    25
2   300     2    25     2    23
3   400     2    25     4    21
4   500     1    25     6    19
5   600     2    25     7    18
6   700     2    25     9    16
7   800     1    25    11    14
8  1300     1    25    12    13

編輯2:包括IceCreamToucan的解決方案,該解決方案無需生成臨時列:

data %>% mutate(
     r_j2 = coalesce(lag(r_j - cumsum(s_j)), r_j)
     )
# A tibble: 8 x 4
     LM   s_j   r_j  r_j2
  <dbl> <dbl> <dbl> <dbl>
1   100     2    25    25
2   300     2    25    23
3   400     2    25    21
4   500     1    25    19
5   600     2    25    18
6   700     2    25    16
7   800     1    25    14
8  1300     1    25    13

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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