Reputation: 415
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!
Upvotes: 4
Views: 548
Reputation: 887118
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))
Upvotes: 2
Reputation: 14764
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
Upvotes: 0
Reputation: 39858
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
Upvotes: 2