What is the best way to perform operations on a newly assigned variable in dplyr?

86 Views Asked by At

How to avoid assigning a value to a variable, then calling it separately right after to manipulate it? (Like so:)

df.3 <- filter(df.1, !(Patient_ID %in% df.2))

df.3 %>%  count(MIPSGroup)

The only way I know how to do it is:

(df.3 <- filter(df.1, !(Patient_ID %in% df.2))) %>%
   df.3 %>%  count(MIPSGroup)

But there's gotta be a better way...

Thanks!

1

There are 1 best solutions below

0
Ben Bolker On

If you were willing to modify the original input, you could use magrittr's %<>% (compound assignment) operator:

(mtcars %<>% filter(cyl==6)) %>% count(mpg)

This modifies the value of mtcars according to the filter and prints the results of the count operation on the result.

There may be some way to use magrittr's other operators (e.g. %T>%) to get this done, but I haven't figured it out yet. I tried

((mtcars -> tmpcars) %<>% filter(cyl==6)) %>% count(mpg)

but R's parsing magic can't quite handle it.