dplyr broadcasting single value per group in mutate

前端 未结 1 1817
庸人自扰
庸人自扰 2020-12-06 03:22

I am trying to do something very similar to Scale relative to a value in each group (via dplyr) (however this solution seems to crash R for me). I would like to replicate a

相关标签:
1条回答
  • 2020-12-06 03:44

    Do this:

    data %>% group_by(category) %>%
      mutate(value2 = value[year == 2000])
    

    You could also do it this way:

    data %>% group_by(category) %>%
      arrange(year) %>%
      mutate(value2 = value[1])
    

    or

    data %>% group_by(category) %>%
      arrange(year) %>%
      mutate(value2 = first(value))
    

    or

    data %>% group_by(category) %>%
      mutate(value2 = nth(value, n = 1, order_by = "year"))
    

    or probably several other ways.

    Your attempt with mutate(value = filter(data, year==2002)) doesn't make sense for a few reasons.

    1. When you explicitly pass in data again, it's not part of the chain that got grouped earlier, so it doesn't know about the grouping.

    2. All dplyr verbs take a data frame as first argument and return a data frame, including filter. When you do value = filter(...) you're trying to assign a full data frame to the single column value.

    0 讨论(0)
提交回复
热议问题