0

I have the following dataframe

    Class  Behavior   mean  
1     BH Baseline     5   
2     BH     Drnk     3   
3     BH      Lvr     2
4     BH     Tone     1
5     NB Baseline     6
6     NB     Drnk     3
7     NB      Lvr     2

I want to generate a new column where I have calculated the difference from baseline for each class and behavior so for example:

    Class  Behavior   mean  diff  
1     BH Baseline     5      0
2     BH     Drnk     3      2
3     BH      Lvr     2      3 
4     BH     Tone     1      4
5     NB Baseline     6      0
6     NB     Drnk     3      3
7     NB      Lvr     2      4

For each level of class, I want look at the difference between Baseline and all other Behaviors. I tried somethings using dplyr but I am just not sure how to make calculations across factor Baseline. Your help is appreciated.

Cath
  • 23,906
  • 5
  • 52
  • 86
Stella
  • 15
  • 3

1 Answers1

1

With the sample input

dd<-read.table(text="    Class  Behavior   mean  
1     BH Baseline     5   
2     BH     Drnk     3   
3     BH      Lvr     2
4     BH     Tone     1
5     NB Baseline     6
6     NB     Drnk     3
7     NB      Lvr     2", header=T)

You can get the desired output easily using dplry

library(dplyr)
dd %>% group_by(Class) %>% 
    mutate(diff=mean[Behavior=="Baseline"]-mean)
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Looks like you are trying to load both `plyr` and `dplyr`. The order in which you load those matters. Make sure you load `plyr` first. – MrFlick May 16 '17 at 23:27