firmo23
firmo23

Reputation: 8404

Group by the position and not by the name of a column in a dataframe

In the code below I group_by() the Pop column. How can I modify the code in order not to use Pop but the fist column of the dataset to group_by()

library(janitor)
library(dplyr)
Pop<-c("p","p","p","p","p","p","p","p")
RC<-c("a","b","c","c","d","d","f","f")
MM<-c(10,9,8,27,9,10,23,42)
UT<-c(5,3,6,14,7,9,45,61)

df<-data.frame(Pop,RC,MM,UT)
tor <- df %>% group_by(Pop) %>% group_modify(~ .x %>% adorn_totals()) %>% ungroup  

tor <- df %>% group_by(df[,1]) %>% group_modify(~ .x %>% adorn_totals()) %>% ungroup  

Upvotes: 2

Views: 37

Answers (2)

akrun
akrun

Reputation: 886938

If it is a single column to group, we may also use .data with the first column name

library(dplyr)
df %>%
   group_by(.data[[first(names(.))]])

-output

# A tibble: 8 × 4
# Groups:   Pop [1]
  Pop   RC       MM    UT
  <chr> <chr> <dbl> <dbl>
1 p     a        10     5
2 p     b         9     3
3 p     c         8     6
4 p     c        27    14
5 p     d         9     7
6 p     d        10     9
7 p     f        23    45
8 p     f        42    61

Upvotes: 1

harre
harre

Reputation: 7277

You would want to use across within group_by:

library(dplyr)

df |>
  group_by(across(1))

Output:

# A tibble: 8 × 4
# Groups:   Pop [1]
  Pop   RC       MM    UT
  <chr> <chr> <dbl> <dbl>
1 p     a        10     5
2 p     b         9     3
3 p     c         8     6
4 p     c        27    14
5 p     d         9     7
6 p     d        10     9
7 p     f        23    45
8 p     f        42    61

Upvotes: 2

Related Questions