0

Here is a beginner's problem:

I like using summarise(), but sometimes I find it difficult storing the results. For example, I know I can store 1 value in the following manner:

stdv <- Data %>%
 filter(x == 1) %>%
 summarise(stdv = sd(y))

But I get in trouble if I try to do so for more than 1 variable. I think it's something to do with creating a vector o variables in the beginning but this doesn't work:

c(dog, cat) <- Data %>%
 filter(x == 1) %>%
 summarise(dog = sd(y),
           cat = mean(y))

Can someone help? Thank ya

  • Welcome! What does `Data %>% filter(x == 1) %>% summarise(dog = sd(y), cat = mean(y))` return? – 9314197 Jun 02 '20 at 13:12
  • This assignment operation looks very pythonic. In R you can only assign to one variable at a time. `Data %>% filter(x == 1) %>% summarise(dog = sd(y), cat = mean(y))` should return a data frame, which you can assign to one variable. – shs Jun 02 '20 at 13:14
  • Does this answer your question? [Summarizing multiple columns with dplyr?](https://stackoverflow.com/questions/21644848/summarizing-multiple-columns-with-dplyr) – Pietro Jun 02 '20 at 13:15
  • What is your expected output? Perhaps replace `c(dog, cat) <-` with `df <- ` to store your output in a data.frame? – Martin Gal Jun 02 '20 at 13:15
  • If you really want to assign to two variables at once, use the `zeallot` package. Look [here](https://stackoverflow.com/a/45329855/11932936) for a short explanation. – shs Jun 02 '20 at 13:18
  • There are packages which allow multiple assignment in R, but for what it's worth that functionality is intentionally not included in tidyverse (of which dplyr is a part) because it's thought that assigning to a single object is better. You can of course still access columns of output individually as e.g. `output_name$column_name` – IceCreamToucan Jun 02 '20 at 13:18

2 Answers2

0

You can store it in a vector like this:

save_vector <- df %>% 
  summarise(dog = sd(id),
            cat = var(id)) %>% 
  unlist()
save_vector 

#     dog      cat 
#1.636392 2.677778 

Data

structure(list(id = c("1", "4", "3", "4", "6", "3", "5", "6", 
"2", "3")), row.names = c(NA, -10L), class = c("tbl_df", "tbl", 
"data.frame"))
Ahorn
  • 3,686
  • 1
  • 10
  • 17
0

We can use base R methods

with(df, c(dog = sd(id), cat = var(id)))
#    dog      cat 
#1.636392 2.677778 

data

df <- structure(list(id = c("1", "4", "3", "4", "6", "3", "5", "6", 
"2", "3")), row.names = c(NA, -10L), class = c("tbl_df", "tbl", 
"data.frame"))
akrun
  • 874,273
  • 37
  • 540
  • 662