create a variable that is a particular observation within the group

Dear Rstudio Community members,

I am very new at Rstudio, hence I apologize in advance for this question.

I have constructed a panel data frame.

Data structure is something like this:

Y Treatment Time ID
1 0 1 1
3 1 2 1
7 1 3 1
9 0 1 2
10 0 2 2
13 0 3 2

Now I want to create a variable Z, that gives the value of Y for time period 3, for every period by ID group.
So the variable Z should look like this:

Y Treatment Time ID Z
1 0 1 1 7
3 1 2 1 7
7 1 3 1 7
9 0 1 2 13
10 0 2 2 13
13 0 3 2 13

I tried many different things, ifelse() statement and mutate(), but with no success.
I hope someone can help me.

Best,

Max

library(tidyverse)

(df_1 <- tribble(
  ~Y, ~Treatment, ~Time, ~ID,
  1, 0, 1, 1,
  3, 1, 2, 1,
  7, 1, 3, 1,
  9, 0, 1, 2,
  10, 0, 2, 2,
  13, 0, 3, 2
))

(df_t_3 <- filter(
  df_1,
  Time == 3
) %>% select(ID, Y) %>%
  rename(Z = Y))

(final_df <- left_join(df_1,
                      df_t_3))

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.