R:从每个组的第一行减去行
我想从列距离中的每个组中的第一行减去每个行。
我的数据如下:
structure(list(Group = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
2L, 3L, 3L, 3L, 3L, 3L), Distance = c(0.05, 0.084, 0.06, 0.03,
0.034, 0.0534, 0.034, 0.23, 0.34, 0.6435, 0.6346, 0.234, 0.246,
0.4, 0.7)), class = "data.frame", row.names = c(NA, -15L))
我尝试了以下代码:
Data <- Data %>%
group_by(Group) %>%
mutate(Difference=Distance - dplyr:: lag(Distance))
但是,如何调整代码,以使每个组的列中的值与每个组的第一行中的值减去列距离中的值? 因此,对于第1组而言,这意味着值0.084、0.06、0.03和0.034都是从0.05中减去的。
I would like to subtract each rows from the first row in each Group for the column Distance.
My data is the following:
structure(list(Group = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
2L, 3L, 3L, 3L, 3L, 3L), Distance = c(0.05, 0.084, 0.06, 0.03,
0.034, 0.0534, 0.034, 0.23, 0.34, 0.6435, 0.6346, 0.234, 0.246,
0.4, 0.7)), class = "data.frame", row.names = c(NA, -15L))
I have tried the following code:
Data <- Data %>%
group_by(Group) %>%
mutate(Difference=Distance - dplyr:: lag(Distance))
However, how can I adjust the code so that for each Group the value in column Distance is subtracted from the value in the first row for each group?
So for group 1 it would mean that the values 0.084, 0.06, 0.03 and 0.034 are all subtracted from 0.05.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更新:请参阅评论:
非常感谢@gregor Thomas:
好的,现在我也看到了。它与
dplyr
方式的评论中提供的格雷戈尔·托马斯(Gregor Thomas)是相同的解决方案!第一个答案:
这是另一个
dplyr
选项:Update: see comments:
Many thanks to @Gregor Thomas:
Ok now I see it also. It is the same solution as Gregor Thomas provided in the comments just in
dplyr
way!First answer:
Here is another
dplyr
option:一个可能的解决方案:
A possible solution: