-1
df1 <- mtcars %>%
    group_by(gear) %>%
    summarise(Mittelwert = mean(mpg, na.rm = TRUE))
df1

df2 <- mtcars %>%
    group_by(mtcars[[10]]) %>%
    summarise(Mittelwert = mean(mtcars[[1]]), na.rm = TRUE)
df2

The last code gives me the mean of the whole data.frame. Since this code is used in a loop, i need to use brackets. Can you help me to get a dynamic code with valid results?

  • [How to make a great R reproducible example?](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) Include packages that you're using; used input (`weights`); wanted output. Also, what loop (over what are you iterating)? Why you use `[[6]]` with `[[41]]`, what's logic behind that? – pogibas May 24 '18 at 08:04

1 Answers1

0

We can use group_by_at and summarise_at to specify column number if we want to avoid using names.

library(dplyr)
mtcars %>%
  group_by_at(10) %>%
  summarise_at(1, mean, na.rm = TRUE)

# A tibble: 3 x 2
#   gear   mpg
#  <dbl> <dbl>
#1  3.00  16.1
#2  4.00  24.5
#3  5.00  21.4

which is equivalent to

mtcars %>%
    group_by(gear) %>%
    summarise(Mittelwert = mean(mpg, na.rm = TRUE))

#   gear Mittelwert
#  <dbl>      <dbl>
#1  3.00       16.1
#2  4.00       24.5
#3  5.00       21.4
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213