Rilcon42
Rilcon42

Reputation: 9763

correct way to calculate factor means using dplyr

How can I get the mean of 'bfat' for each level of 'age' given a level of 'drug' (in this case when drug==1)? I tried this:

require(dplyr)
df<-data.frame(drug=c(1,1,1,1,2),age=c(1,2,3,1,1),bfat=c(10,30,3,4,7))
noDrug<-df%>%split(drug==1) #get only drug ==1
noDrug<-as.data.frame(noDrug$'TRUE')
mean.bfat.per.level.of.age <- noDrug%>%group_by(age) %>% summarise(mean(bfat)) #when drug==1

I expected to get 3 values:

age1 mean bfat when drug=1: 7 
age2 mean bfat when drug=1: 30             
age3 mean bfat when drug=1: 3

Upvotes: 2

Views: 1400

Answers (1)

akrun
akrun

Reputation: 887851

We filter the rows where 'drug' is 1, then group by 'age', and get the mean of 'bfat'.

df %>% 
   filter(drug==1) %>%
   group_by(age) %>% 
   summarise(bfat= mean(bfat))
#  age  bfat
#  (dbl) (dbl)
#1     1     7
#2     2    30
#3     3     3

If both plyr and dplyr were loaded, change the last line of code to

-- %>%
   dplyr::summarise(bfat = mean(bfat))

Upvotes: 2

Related Questions