我在一行中有一个带有数值的数据格式。现在我要计算这些行的累积和,直到>= 1。如果达到这一点,所有这些行都打印为计数器,在每一行中写入其计数器的累计和,然后查找下一行的累积和。
应该是这样的:
value counter cumsum
0.3 1 0.9
0.3 1 0.9
0.3 1 0.9
0.3 2 0.4
0.1 2 0.4
2 3 2我的问题是如何告诉R停止累积和,如果>=大于1,有什么想法吗?提前谢谢你。
发布于 2022-03-09 18:20:16
我不知道我是否正确地理解了你的问题,但也许这里的这个问题是有帮助的:
value = round(runif(20, min = 0.1, max = 0.5), 1)
csumVec = numeric(length(value))
counterVec = numeric(length(value))
startIndex = 1
csum = 0
counter = 1
for(i in 1:length(value)) {
csum = csum + value[i]
if(csum > 1) {
counterVec[startIndex:i] = counter
csumVec[startIndex:i] = csum-value[i]
startIndex = i
counter = counter+1
csum = value[i]
}
if(i == length(value)) {
counterVec[startIndex:i] = counter
csumVec[startIndex:i] = csum
}
}
cbind(value, counterVec, csumVec)发布于 2022-03-09 20:27:21
似乎您可以计算累积和,除以1,并取floor() (四舍五入)
floor(cumsum(value) / 1)
## [1] 0 0 0 1 1 3这是正确的,只是它是基于0的,并且counter不会增加1。
counter0 = floor(cumsum(value) / 1)
counter = match(counter0, unique(counter0))
counter
## [1] 1 1 1 2 2 3得到“棘手”部分后,我将使用dplyr (library(dplyr))作为其余部分
## library(dplyr)
tibble(value, counter) |>
mutate(cum_sum = cumsum(value)) |>
group_by(counter) |>
mutate(cumsum = max(cumsum(value)))
## # A tibble: 6 × 3
## # Groups: counter [3]
## value counter cumsum
## <dbl> <int> <dbl>
## 1 0.3 1 0.9
## 2 0.3 1 0.9
## 3 0.3 1 0.9
## 4 0.3 2 0.4
## 5 0.1 2 0.4
## 6 2 3 2或者在(更一般的)函数中捕获棘手的部分。
cumgroup <- function(x, upper = 1) {
counter0 = floor(cumsum(x) / upper)
match(counter0, unique(counter0))
}并将其并入dplyr解决方案
tibble(value) |>
mutate(counter = cumgroup(value)) |>
group_by(counter) |>
mutate(cumsum = max(cumsum(value)))或者取决于你到底想要什么
tibble(value) |>
mutate(
cumsum = cumsum(value) %% 1,
counter = cumgroup(value)
) |>
group_by(counter) |>
mutate(cumsum = max(cumsum)) |>
select(value, counter, cumsum)https://stackoverflow.com/questions/71413918
复制相似问题