Marco Mello
Marco Mello

Reputation: 175

weighted mean between two specific rows

I have a dataframe of this form

id  value
1   10
2   25
5   30
7   15
9   30
10  50

I would like to transform it in the following way

    id    value
    1     10
    2     25
    5     30
    9     30
    7+10  43

where the obs with id "7+10" is the weighted mean of the previous obs for 7 and 10 with weights 0.2 and 0.8, in other words 43=0.2*15+0.8*50. I tried to use the function aggregate to do this, but it does not work. What can I use to make operations between specific rows?

Thank you for your help.

Upvotes: 0

Views: 35

Answers (1)

prosoitos
prosoitos

Reputation: 7327

Since it is a lot easier to work with variables than with rows, you can transform your data from the long to the wide format with the package tidyr (part of the tidyverse), make your transformations, then back to the long format again with tidyr:

library(tidyverse)

dat <- tibble(
  id = c(1, 2, 5, 7, 9, 10),
  value = c(10, 25, 30, 15, 30, 50)
)

dat %>%
  spread(id, value) %>%
  mutate(`7 + 10` = 0.2 * `7` + 0.8 * `10`) %>%
  select(- `7`, - `10`) %>%
  gather("id", "value", everything())

  id     value
  <chr>  <dbl>
1 1         10
2 2         25
3 5         30
4 9         30
5 7 + 10    43

Upvotes: 1

Related Questions