【发布时间】:2020-08-15 11:31:52
【问题描述】:
我有一个这样的数据框:
tdf <- structure(list(indx = c(1, 1, 1, 2, 2, 3, 3), group = c(1, 1,
2, 1, 2, 1, 1)), .Names = c("indx", "group"), row.names = c(NA,
-7L), class = "data.frame")
数据框如下所示:
indx group
1 1 1
2 1 1
3 1 2
4 2 1
5 2 2
6 3 1
7 3 1
我想遍历组,并将第一个索引的组值保留为所需的输出
对于第一个之后 indx 值的每个增量,我想从前一个 indx 中添加组的最大值,并希望从第二个城市开始增加组值。
想要的输出是这样的:
indx group desiredOutput
1 1 1 1
2 1 1 1
3 1 2 2
4 2 1 3
5 2 2 4
6 3 1 5
7 3 1 5
为了清楚起见,我将数据框拆分如下:
indx group desiredOutput
1 1 1 1
2 1 1 1 To be retained as is
3 1 2 2
4 2 1 3 Second index-the max value of desiredOutput in indx1 is 2
5 2 2 4 I want to add this max value to the group value in indx 2
6 3 1 5 Similarly, the max value of des.out of indx2 is 4
7 3 1 5 Adding the max value to group provides me new values
我尝试将这个数据框拆分成一个数据框列表并迭代到每个数据框。
ndf <- split(tdf,f = tdf$indx)
x <- 0
for (i in seq_along(ndf)){
ndf[[i]]$ng <- ndf[[i]]$group+x
x <- max(ndf[[i]]$indx) + 1
}
ndf
上面的代码更新了第二个索引的值,但是当它到达第三个索引时失败了。
【问题讨论】:
标签: r