1

I'm manipulating my data using dplyr, and after grouping my data, I would like to subtract all values by the first or second value in my group (i.e., subtracting a baseline). Is it possible to perform this in a single pipe step?

MWE:

test <- tibble(one=c("c","d","e","c","d","e"), two=c("a","a","a","b","b","b"), three=1:6)
test %>% group_by(`two`) %>% mutate(new=three-three[.$`one`=="d"])

My desired output is:

# A tibble: 6 x 4
# Groups:   two [2]
  one   two   three   new
  <chr> <chr> <int> <int>
1 c     a         1    -1
2 d     a         2     0
3 e     a         3     1
4 c     b         4    -1
5 d     b         5     0
6 e     b         6     1

However I am getting this as the output:

# A tibble: 6 x 4
# Groups:   two [2]
  one   two   three   new
  <chr> <chr> <int> <int>
1 c     a         1    -1
2 d     a         2    NA
3 e     a         3     1
4 c     b         4    -1
5 d     b         5    NA
6 e     b         6     1
Chris
  • 78
  • 7

2 Answers2

6

We can use the first from dplyr

test %>%
   group_by(two) %>% 
   mutate(new=three- first(three))
# A tibble: 6 x 4
# Groups: two [2]
#  one   two   three   new
#  <chr> <chr> <int> <int>
#1 c     a         1     0
#2 d     a         2     1
#3 e     a         3     2
#4 c     b         4     0
#5 d     b         5     1
#6 e     b         6     2

If we are subsetting the 'three' values based on string "c" in 'one', then we don't need .$ as it will get the whole column 'c' instead of the values within the group by column

test %>% 
   group_by(`two`) %>%
   mutate(new=three-three[one=="c"])
akrun
  • 874,273
  • 37
  • 540
  • 662
1
library(tidyverse)

tibble(
  one = c("c", "d", "e", "c", "d", "e"),
  two = c("a", "a", "a", "b", "b", "b"),
  three = 1:6
) -> test_df

test_df %>%
  group_by(two) %>%
  mutate(new = three - three[1])
## # A tibble: 6 x 4
## # Groups:   two [2]
##   one   two   three   new
##   <chr> <chr> <int> <int>
## 1 c     a         1     0
## 2 d     a         2     1
## 3 e     a         3     2
## 4 c     b         4     0
## 5 d     b         5     1
## 6 e     b         6     2
hrbrmstr
  • 77,368
  • 11
  • 139
  • 205