Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr: using filter, group_by, from within mutate command [duplicate]

Tags:

r

dplyr

I want to add a column to the data table that contains each value of y divided by the mean of the corresponding condition in x (1 or 2) where x2 = 1. For the following data where x = 1 y should be divided by 1.4 and where x=2 y should be divided by 1.

dt1 <- data.table(x=c("1","1","1","1","1","1","1","1","1","1","2","2","2","2","2","2","2","2","2","2"),
       x2=c("1","1","2","2","2","2","3","3","3","3","1","1","2","2","2","2","3","3","3","3"), 
       y=c(1.41,1.39,1.9,2.1,0.9,1.1,3.1,2.9,3.9,4.1,0.9,1.1,1.9,2.1,0.9,1.1,3.1,2.9,3.9,4.1))

I can write the mean of x * x2 = 1 to a new file.

mean <- dt1 %>% filter(x2==1) %>% group_by(x) %>% summarise(mean(y))

but I can't work out how to mesh instruct the commands to call the correct value. dt1 %>% mutate(z = y/a reference to 'mean')

I thought creating a new column filled with the values that I want to divide by but once again I can't work out how to call the grouping criteria from within the command.

t <- dt1 %>% mutate(T=ifelse(x==1,(filter(x2==1) %>% group_by(x=1) %>%
     summarise(mean(y))),ifelse(x==1,(filter(x2==2) %>% group_by(x=2) %>% 
     summarise(mean(y))),NA)

I'm not fixed on only using dplyr but I've been using it a lot recently. I'm open to the simplest solution.

like image 381
Michael_A Avatar asked Nov 12 '14 11:11

Michael_A


1 Answers

Try

  left_join(dt1,
            dt1 %>% 
                 filter(x2==1) %>%
                 group_by(x) %>%
                 summarise(a=mean(y)), by='x') %>%
                 mutate(z=y/a)%>%
                 head()

  #  x x2    y   a         z
  #1 1  1 1.41 1.4 1.0071429
  #2 1  1 1.39 1.4 0.9928571
  #3 1  2 1.90 1.4 1.3571429
  #4 1  2 2.10 1.4 1.5000000
  #5 1  2 0.90 1.4 0.6428571
  #6 1  2 1.10 1.4 0.7857143

Or using data.table

library(data.table)
dt2 <- dt1[x2==1,list(a=mean(y)) , by=x]
setkey(dt1, x)
res <- dt1[dt2][,z:=y/a]
head(res)
#   x x2    y   a         z
#1: 1  1 1.41 1.4 1.0071429
#2: 1  1 1.39 1.4 0.9928571
#3: 1  2 1.90 1.4 1.3571429
#4: 1  2 2.10 1.4 1.5000000
#5: 1  2 0.90 1.4 0.6428571
#6: 1  2 1.10 1.4 0.7857143

Update

A more compact option for dplyr as suggested by @aosmith is

  dt1 %>%
      group_by(x) %>% 
      mutate(a=mean(y[x2==1]), z=y/a)
like image 183
akrun Avatar answered Oct 02 '22 15:10

akrun