简体   繁体   中英

R dplyr divide between two rows after group by

I have a data frame like this:

x <- data.frame(
    name = rep(letters[1:4], each = 2),
    value = c(2,10,4,20,8,40,20,100)
)

I want to group by name, then divide the bottom row by upper row.

result should look like:

  name divideValue
1    a           5
2    b           5
3    c           5
4    d           5

Thank you!

You can do:

x %>%
 group_by(name) %>%
 summarise(value = last(value)/first(value))

  name  value
  <fct> <dbl>
1 a         5
2 b         5
3 c         5
4 d         5

We can use data.table

library(data.table)
setDT(x)[, .(value =last(value)/first(value)) , name]

Or with dplyr

library(dplyr)
x %>% 
    group_by(name) %>% 
    summarise(value = value[n()]/value[1])

Or in base R

aggregate(value ~ name, x, FUN = function(x) tail(x, 1)/head(x, 1))

Another option:

x %>%
  group_by(name) %>%
  summarise(value = Reduce(`/`, rev(value)))

Output:

# A tibble: 4 x 2
  name  value
  <fct> <dbl>
1 a         5
2 b         5
3 c         5
4 d         5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM