Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

group_by() is converting dataframe to tibble

I have a problem running st_as_sf() after group_by(). My code isn't working when previously I had no issues.

I discovered that group_by() was converting my dataframe to a tibble and st_as_sf() won't work with tibbles. I had peers run the same code and the conversion from dataframe to tibble did not occur for them. Is this something that's happening because of a new update?

R version 4.0.0, RStudio version 1.3.959.

like image 949
Hannah88 Avatar asked Oct 26 '25 21:10

Hannah88


2 Answers

As of dplyr 1.1.0, you can leverage .by. Using .by instead of group_by() has three main advantages:

  • grouping is applied only to a single operation so no need to ungroup() afterwards
  • original object class() maintained
  • in the case of summarise(), group key sort order is preserved. Note that summarise() does not coerce to tibble, it is group_by() that does that
library(dplyr)

df <- data.frame(x = c("b", "b", "a", "a"),
                 y = 1:4)

df %>% group_by(x) %>%
  summarise(sum_y = sum(y)) %>%
  ungroup()

# # A tibble: 2 × 2
#   x     sum_y
#   <chr> <int>
# 1 a         7
# 2 b         3

df %>%
  summarise(sum_y = sum(y), .by = x)

#   x sum_y
# 1 b     3
# 2 a     7
like image 113
L Tyrone Avatar answered Oct 29 '25 11:10

L Tyrone


This does seem true, at least with a development version of dplyr.

dd <- data.frame(x=rep(1:4,each=5), y=rnorm(20))
library(dplyr)
str(dd %>% group_by(x) %>% ungroup())
## tibble [20 × 2] (S3: tbl_df/tbl/data.frame)
##  $ x: int [1:20] 1 1 1 1 1 2 2 2 2 2 ...
##  $ y: num [1:20] -0.708 0.976 -1.051 -0.97 -0.225 ...

packageVersion("dplyr") is 0.8.99.9002.

I can't speak for how this behaved in previous versions. You could always add an as.data.frame() at the end of your pipeline ...

like image 22
Ben Bolker Avatar answered Oct 29 '25 12:10

Ben Bolker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!