通过与上面的单元进行比较来更改单元格值
我有以下数据框架:
ID year level
1 2000 NA
1 2001 3
1 2002 3
1 2003 2
1 2004 1
2 2000 1
2 2001 3
2 2002 3
2 2003 3
2 2004 3
如果上一个较小,我想根据上一个在“级别”列中按ID更新每个值。
数据帧应该看起来像
ID year level
1 2000 NA
1 2001 3
1 2002 3
1 2003 2
1 2004 1
2 2000 1
2 2001 1
2 2002 1
2 2003 1
2 2004 1
我尝试使用从数据表的移动来尝试的,但它只会更改一个单元格。 我得到了这个结果
ID year level
1 2000 NA
1 2001 3
1 2002 3
1 2003 2
1 2004 1
2 2000 1
2 2001 1
2 2002 3
2 2003 3
2 2004 3
I have the following dataframe:
ID year level
1 2000 NA
1 2001 3
1 2002 3
1 2003 2
1 2004 1
2 2000 1
2 2001 3
2 2002 3
2 2003 3
2 2004 3
I want to update each value in "level" column by ID based on the previous one if the previous one is smaller.
the dataframe should look like this
ID year level
1 2000 NA
1 2001 3
1 2002 3
1 2003 2
1 2004 1
2 2000 1
2 2001 1
2 2002 1
2 2003 1
2 2004 1
I tried using shift from data table but it only changes one cell.
I got this result
ID year level
1 2000 NA
1 2001 3
1 2002 3
1 2003 2
1 2004 1
2 2000 1
2 2001 1
2 2002 3
2 2003 3
2 2004 3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由
Created on 2022-07-06 by the reprex package (v2.0.1)
tidyverse
带有accomeculate()
的解决方案来自purrr
:A
tidyverse
solution withaccumulate()
frompurrr
: