dplyr custom function

Published by onesixx on

custom function after grouping data.fame

 

aa <- rep(c(1, 2), each=5)
bb <- rep(c(1:5), 2) 
cc <- c(1:10)
Df <- data.frame(aa=aa, bb=bb, cc=cc*cc)
   aa bb  cc
1   1  1   1
2   1  2   4
3   1  3   9
4   1  4  16
5   1  5  25
6   2  1  36
7   2  2  49
8   2  3  64
9   2  4  81
10  2  5 100

방법1>

Df %>% group_by(bb) %>%
    mutate(dd = cc[aa==2] - cc[aa ==1])

방법2>

f <- function(aa, cc) cc[aa == 2] - cc[aa == 1]
Df %>% group_by(bb) %>%
  mutate(dd = f(aa, cc))  

 

 

Categories: Reshaping

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x