D Greenwood
D Greenwood

Reputation: 446

Normalising by control condition in each group with plyr

I have a set of data in the following format:

     Rep Day      Drug   GFP_per_cell
1      1  3d      CTRL            2.0
2      1  3d         A            1.0
3      1  3d         B            4.0
4      2  3d      CTRL            3.0
5      2  3d         A            6.0
...

I want to normalise each repeat (Rep) to the control (CTRL) - i.e. to divide all the values for each repeat by the control - to give a dataframe such as:

     Rep Day      Drug   GFP_per_cell
1      1  3d      CTRL            1.0
2      1  3d         A            0.5
3      1  3d         B            2.0
4      2  3d      CTRL            1.0
5      2  3d         A            2.0
...

I have been trying to do this with the mutate function in dplyr, and this is my attempt:

df %>% 
  group_by(Rep) %>% 
  mutate(df = GFP_per_cell / filter(Inhibitor == "CTRL")[,GFP_per_cell])

But this gives me the error:

Error: no applicable method for 'filter_' applied to an object of class "logical"

How can I ask mutate to divide by the 'CRTL' condition in each group?

Upvotes: 1

Views: 253

Answers (1)

akrun
akrun

Reputation: 887501

If there is only a single 'CTRL' per each group of 'Rep', then subset the 'GFP_per_cell' that corresponds to 'CTRL' in the 'Drug' (by converting to logical vector) and use that to normalize the 'GFP_per_cell'

df %>% 
    group_by(Rep) %>%
    mutate(GFP_per_cell = GFP_per_cell/GFP_per_cell[Drug=="CTRL"])
#   Rep   Day  Drug GFP_per_cell
#  <int> <chr> <chr>        <dbl>
#1     1    3d  CTRL          1.0
#2     1    3d     A          0.5
#3     1    3d     B          2.0
#4     2    3d  CTRL          1.0
#5     2    3d     A          2.0

Upvotes: 2

Related Questions