簡體   English   中英

如果在 2 行中滿足某些條件,如何在 R 數據框中添加新列,顯示當前行和前一行中的值之和?

[英]How to add new column in R data frame showing sum of a value in a current row and a prior row, if certain conditions are met in the 2 rows?

假設您有一個由“a”和“b”列組成的數據框,其值如下所示,由df <- data.frame(a=c(0, 1, 2, 2, 3), b=c(1, 3, 8, 9, 4)) 假設您要添加“c”列,如果“a”中的值等於“a”列中前一行的值,則將“b”列中的相應行值相加; 否則顯示 0 值。 下面添加了一個“c”列來說明我正在嘗試做的事情:

   a  b   add col c
1  0  1       0
2  1  3       0
3  2  8       0
4  2  9       17 (since the values in col "a" rows 3 and 4 are equal, add the values in col b rows 3 and 4)
5  3  4       0

在本機 R 中執行此操作的最簡單方法是什么?

我們可以用

 df %>% group_by(a) %>% mutate(c = if(n() > 1) sum(b) else 0)

暫無
暫無

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

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