MasterShifu
MasterShifu

Reputation: 233

Group by multiple columns and assign value from another column in R

I have a dataset like below in R:

enter image description here

I want to add a new column "Starting output" which basically gets the value from the output column at Time = 0 but also groups them by Temperature. A sample solution is below: enter image description here

I tried the below code but it just worked for the first batch and doesn't work with all batches. df$Output[df$Time == 24 | df$Time == 48 ] <- df$Output[df$Time == 0]

I tried to use group_by() and mutate but haven't had any success with this. Any help is appreciated!

Upvotes: 0

Views: 680

Answers (1)

zimia
zimia

Reputation: 932

df %>%
  group_by(Temp) %>%
  mutate(`Starting Output` = ifelse(Time==0, Output, NA)) %>%
  tidyr::fill(`Starting Output`, .direction = "down") %>%
  ungroup()

# A tibble: 6 x 5
  Batch  Temp  Time Output `Starting Output`
  <chr> <dbl> <dbl>  <dbl>             <dbl>
1 A        15     0     12                12
2 A        15    24     34                12
3 A        15    48     36                12
4 A        25     0     13                13
5 A        25    24     22                13
6 A        25    48     24                13

Upvotes: 1

Related Questions