Ross R
Ross R

Reputation: 9403

dplyr: How to summarize results to a variable (not a table)

I want to summarize some data and store the resulting value in a variable, not in a table. So, something like this:

result <- filter(data, cond==TRUE) %>%
    summarize(result = col1 / col2) %>%
    RETURN_COL(result)

Is there a way to do that?

Upvotes: 0

Views: 1146

Answers (1)

talat
talat

Reputation: 70336

You can use magrittr's "exposition pipe-operator" which is %$%. Here's a reproducuble example:

library(magrittr)
library(dplyr)

result_variable <- iris %>% 
  filter(Species == "setosa") %>%
  mutate(result = Sepal.Length / Sepal.Width) %$%   # use magrittr's %$% operator to extract the result vector
  result

Then check the resulting vector:

> str(result_variable)
# num [1:50] 1.46 1.63 1.47 1.48 1.39 ...
> is.atomic(result_variable)
# [1] TRUE

Upvotes: 3

Related Questions