0

I have the following code:

data <- c(62, 60, 63, 59, 63, 67, 71, 64, 65, 66, 68, 66, 
          71, 67, 68, 68, 56, 62, 60, 61, 63, 64, 63, 59)
grp <- factor(rep(LETTERS[1:4], c(4,6,6,8)))
de <- data.frame(group=grp, dt=data)

de %>% 
  group_by(group) %>% 
  summarize(mean = mean(dt),
            sum = sum(dt))

The code runs well. But I have one questions:

How to store the output result as a dataframe and assign name to it?

Thank you!

vicky
  • 395
  • 1
  • 3
  • 15
  • ```de %>% group_by(group) %>% summarize(mean = mean(dt), sum = sum(dt)) %>% as.data.frame -> de.saved``` – M-- Oct 09 '19 at 21:27
  • 2
    Possible duplicate of [convert scientific notation to numeric, preserving decimals](https://stackoverflow.com/questions/44725001/convert-scientific-notation-to-numeric-preserving-decimals) – M-- Oct 09 '19 at 21:27
  • Thank you! adding %>% as.data.frame works. However, do you know how to assign a name (df) to this dataframe? so that if I call df it will print out – vicky Oct 09 '19 at 21:35
  • 1
    I'd recommend that if you're having trouble assigning a variable, you first take a step back, go through some basic R tutorials, and then come back to the specific question. Assigning a variable is one of the first things you learn in any language; in R it's done like `x <- "whatever"` or `x = "whatever"` – camille Oct 09 '19 at 22:06
  • `df` is just the name. you can save it as `de.saved` that I had in my first comment or `dataframeofmine` or whatever. ```de %>% group_by(group) %>% summarize(mean = mean(dt), sum = sum(dt)) %>% as.data.frame -> df``` – M-- Oct 09 '19 at 22:18

2 Answers2

2

Another suggestion: Use <- to assign df to global environment.

df <- de %>% 
group_by(group) %>%
summarize(mean = mean(dt),
sum = sum(dt)) %>%
mutate_if(is.numeric, round, 2). # changes 2 to the desired number of decimals 
On_an_island
  • 387
  • 3
  • 16
  • Thank you! I'm adding %>% as.data.frame at the end, and it worked. But do you know how to assign a name to this dataframe so that I can call it later? – vicky Oct 09 '19 at 21:41
  • Yes, use the `<-` operator to assign a unique name to your dataframe. So in the example I posted you could call your df by typing `df` in the console or other scripts you're working on. `<-` operator stores objects like dataframes to Rs global environment. – On_an_island Oct 09 '19 at 21:43
1

We can use the options to change the printing of scientific format

options(scipen = 999)
dout <- de %>% 
            group_by(group) %>% 
            summarize(mean = mean(dt),
            sum = sum(dt))
akrun
  • 874,273
  • 37
  • 540
  • 662