Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201894

How to overwrite values after grouping in R but preserving the initial value for the group

$
0
0

I would like to do a simple overwriting in R, but I guess is not as simple as I thought it would be. I have a beginning, an end, a majorCategory and a subCategory. For every majorCategory, there is a beginning and an end. I have the length of the majorCategory and I calculate the length of the subcategories, and from now on I am stuck because I would like to overwrite the beginnings and the ends for the subcategories but at the same time preserve the initial beginnings for the majorCategory . How do I do that?

 df <- structure(list(majorCat = structure(c(1L, 1L, 1L, 1L, 1L, 1L,  1L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 
 1L), .Label = c("Major_A", "Major_B"), class = "factor"), begin = c(60, 60, 60, 60, 60, 60, 60,60,60, 
 60, 20, 20, 20, 20, 20), end = c(75, 75, 75, 75, 75, 75, 75, 75, 75, 75, 80, 80, 80, 80, 80), subCat 
 = c("d", "b", "c", "e", "a", "b", "e", "a", "d", "b", "d", "b", "d", "e", "b")), row.names = c("1", 
 "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"), class = "data.frame")


  library(dplyr)
  df %>% 
     group_by(begin, end, subCat) %>% 
     summarise(countt = n()) %>% 
     mutate(percc = countt/sum(countt),
     lengthh = end - begin,
     lengthhSubCat = lengthh * percc) %>% select(begin, end, lengthh , lengthhSubCat)

enter image description here

I would very much like to get to this:
enter image description here

Thank you very very much for your time!


Viewing all articles
Browse latest Browse all 201894

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>