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

How to work with special row after group_by in R

$
0
0

I have a data frame something like bellow:

amount <- sample(10000:2000, 20)
year<- sample(2015:2017, 20, replace = TRUE)
company<- sample(LETTERS[1:3],20, replace = TRUE)
df<-data.frame(company, year, amount)

Then I want to group by company and year so I have:

df %>%
  group_by(company, year) %>%
  summarise(
    total= sum(amount)
     )

  company  year total
  <fct>   <int> <int>
1 A        2015  1094
2 A        2016  3308
3 A        2017  4785
4 B        2015  1190
5 B        2016  6583
6 B        2017  1964
7 C        2015  4974
8 C        2016  1986
9 C        2017  3465

Now, I want to divide the last row in each group to the first row. In other words, I want to divide the total value for the last year for each company to the same value of the first year.

Thanks.


Viewing all articles
Browse latest Browse all 209912


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