简体   繁体   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?

Suppose you have a data frame of columns "a" and "b" with the values shown below, generated with df <- data.frame(a=c(0, 1, 2, 2, 3), b=c(1, 3, 8, 9, 4)) .假设您有一个由“a”和“b”列组成的数据框,其值如下所示,由df <- data.frame(a=c(0, 1, 2, 2, 3), b=c(1, 3, 8, 9, 4)) Suppose you want to add a column "c", whereby if a value in "a" equals the value in the immediately preceding row in col "a", then the corresponding row values in col "b" are summed;假设您要添加“c”列,如果“a”中的值等于“a”列中前一行的值,则将“b”列中的相应行值相加; otherwise a 0 value is shown.否则显示 0 值。 A column "c" is added to the below to illustrate what I'm trying to do:下面添加了一个“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

What is the easiest way to do this in native R?在本机 R 中执行此操作的最简单方法是什么?

We can use我们可以用

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 R:在满足条件的行中查找一个值,将某些数字添加到该值,然后在该行的另一列中创建一条消息 - R: Find a value in rows met a condition, add certain numbers to the value, and then create a message in that row in another column R data.table/frame 中不同列中前行值与当前行值的总和比率 - Sum ratios of previous rows values over current row value in a different column by groups in R data.table/frame 满足条件时将行值替换为其他行的总和 - Replace a row value with sum of other rows when conditions are met 在 R 中查找包含特定值的行中数据框列的总和 - Finding sum of data frame column in rows that contain certain value in R 将不同的列值行求和到R中的新列行 - sum different column value rows into a new column row in R 如何在复杂的“if”条件下使用数据框中的前一行值来确定 R 中的当前值 - How to use previous row value in a data frame for complicated 'if' conditions to determine current value in R 在 R 中的数据框中创建一个包含 1 列值总和的新行 - Create a new row with 1 - sum of column values in a data frame in R R - 将行添加到计算列中所有值的总和的数据框中 - R - add row to a data frame that calculates sum of all values in a column Q-如何通过R中的两个条件基于行值在data.frame中填充新列 - Q-How to fill a new column in data.frame based on row values by two conditions in R 将新列添加到数据框并使用特定逻辑的值填充行 - Add new column to data frame and populate the row with value from a certain logic
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM