How to use the mutate function to build a new column which has the value based on another column?

Viewed 29

My data frame looks like this:

df <- data.frame(group = c(rep("A",5), rep("B",4)),
                 number = c(7,6,4,1,7, 9,5,2,8),
                 tf = c(F,F,T,F,F,F,F,F,T))

Now I want to add a new column which group the data by group, then have the value equals to the number which have the tf == T (for each group there is only one T). I expect the result like this:

  group number    tf new
1     A      1 FALSE   4
2     A      2 FALSE   4
3     A      3  TRUE   4
4     A      4 FALSE   4
5     A      5 FALSE   4
6     B      1 FALSE   8
7     B      2 FALSE   8
8     B      3 FALSE   8
9     B      4  TRUE   8

I was wondering how can I do that.

1 Answers

Just use the logical column for indexing

library(dplyr)
df %>%
    group_by(group) %>%
    mutate(new = number[tf][1]) %>% 
    ungroup

-output

# A tibble: 9 x 4
  group number tf      new
  <chr>  <dbl> <lgl> <dbl>
1 A          7 FALSE     4
2 A          6 FALSE     4
3 A          4 TRUE      4
4 A          1 FALSE     4
5 A          7 FALSE     4
6 B          9 FALSE     8
7 B          5 FALSE     8
8 B          2 FALSE     8
9 B          8 TRUE      8

If we want to change the 'number' to sequence values

df %>%
    group_by(group) %>%
    mutate(new = number[tf][1], number = row_number()) %>% 
    ungroup

-output

# A tibble: 9 x 4
  group number tf      new
  <chr>  <int> <lgl> <dbl>
1 A          1 FALSE     4
2 A          2 FALSE     4
3 A          3 TRUE      4
4 A          4 FALSE     4
5 A          5 FALSE     4
6 B          1 FALSE     8
7 B          2 FALSE     8
8 B          3 FALSE     8
9 B          4 TRUE      8
Related