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.
-
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. -
All
dplyr
verbs take a data frame as first argument and return a data frame, includingfilter
. When you dovalue = filter(...)
you’re trying to assign a full data frame to the single columnvalue
.