首页 > 解决方案 > Calculate cumulative (100%) percentage from column cumulative range

问题描述

I have a unique question about calculating cumulative percentages in my dataframe below.

dtFMCount <- c(6, 21, 3, 11, 1, 3, 44, 2, 4, 1)
dtTotDur <- c(607142.353, 96240.799, 79624.690, 78672.113, 30265.219, 15037.119, 14870.920, 8470.878, 7305.159, 4126.279)

DF <- data.frame(dtFMCount, dtTotDur)

summ <- sum(DF$dtTotDur)
DF$Cumm <- round((100 * DF$dtTotDur/summ), digits = 2)

Using the above code I can get a DF like this with the DT$Cumm column as a cumalitve of the summ of DF$dtTotdur.

enter image description here

What I wanting to do is add another column DF$Cumm2 that would show a cumulative based of a 100% scale. I can do in excel see below.

enter image description here

So, I have tried a few different things, but it does not give me what I want. The below code and variations of it but not getting the result.

DF <- DF %>% group_by(dtFMCount, dtTotDur) %>% summarise(proportion = n()) %>%
mutate(Perc = cumsum(100*proportion/sum(proportion))) %>%
select(-proportion)

Any help with this in either a data.frame or data.table formats would help and Thanks for your help all.

标签: rdataframe

解决方案


我们可以做的

library(dplyr)
df %>% 
     mutate(New = cumsum(Cumm))

推荐阅读