我有一个这样的数据框:
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
上面的代码更新了第二个索引的值,但是到达第二个索引时失败。
首先,找到每个索引的最大组值,然后计算这些组的累积总和。
library(dplyr)
maxGroupVals <- tdf %>%
group_by(indx) %>%
summarise(maxVal = max(group)) %>%
mutate(indx = indx + 1, maxVal = cumsum(maxVal))
将1加到索引中,因为这是将这些最大值添加到的索引。连接数据框将为您提供目标增长的列。然后,它是带有条件语句的简单mutate,用于处理index = 1的情况。
tdf %>%
left_join(maxGroupVals) %>%
mutate(desiredOutput = if_else(indx == 1, group, group + maxVal)) %>%
select(-maxVal)
如果需要,请删除中间计算列。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句