Calculate Percentage for each time series observations per Group in R

前端 未结 2 619
感动是毒
感动是毒 2020-12-07 03:37

New to R, so just my getting head around the data wrangling aspect. Tried looking for a similar question but couldn\'t find it.

I would like to add an additional c

2条回答
  •  再見小時候
    2020-12-07 03:52

    library(dplyr)
    df %>% group_by(date) %>% mutate( percentage = views/sum(views))
    Source: local data frame [9 x 4]
    Groups: date
    
      views       date article percentage
    1  1578 2015-01-01       A  0.5698808
    2   616 2015-01-01       B  0.2224630
    3   575 2015-01-01       C  0.2076562
    4  1744 2015-01-02       A  0.5921902
    5   541 2015-01-02       B  0.1837012
    6   660 2015-01-02       C  0.2241087
    7  2906 2015-01-03       A  0.6955481
    8   629 2015-01-03       B  0.1505505
    9   643 2015-01-03       C  0.1539014
    

    Or, if multiple identical articles are possible per day:

    df %>% group_by(date) %>% mutate(sum = sum(views)) %>% 
    group_by(date, article) %>% mutate(percentage = views/sum) %>% 
    select(-sum)
    

提交回复
热议问题