group_modify() lost the sf attributes in data.frame?

library(sf)
library(tidyverse)
library(gganimate)

# map data
nc <- st_read(system.file("shape/nc.shp", package = "sf"))


# simulate data (two day data for 20 city)
d <- bind_rows(
  tibble(
     time = "day1",
     NAME = sample(nc$NAME, size = 20, replace = F),
    value = sample(1:10,    size = 20, replace = T)
  ),
  tibble(
     time = "day2",
     NAME = sample(nc$NAME, size = 20, replace = F),
    value = sample(21:30,   size = 20, replace = T)
  )
)



# combine

# g <- d %>%
# 	left_join(nc, ., by = "NAME")
# 
# g <- d %>%
# 	full_join(nc, ., by = "NAME")


g <- d %>%
  group_by(time) %>%
  group_modify(
    ~ left_join(nc, ., by = "NAME")
  )



# want to visual
g %>%
  ggplot() +
  geom_sf(aes(fill = value)) +
  labs(title = "{closest_state}") +
  transition_states(
    time,
    transition_length = 1,
    state_length = 3
  )

in dplyr document:

> group_modify() returns a grouped tibble. In that case .f must return a data frame.
  • left_join(nc, d, by = "NAME") %>% class() indeed return "sf" and "data frame". However, when using in group_modify(), why not support data frames with the sf property?
  • How to fix it and generate the gganimate?

thank you very much.

g %>% 
  st_as_sf() %>%                  # << 
  ggplot() +
  geom_sf(aes(fill = value)) +
  labs(title = "{closest_state}") +
  transition_states(
    time,
    transition_length = 1,
    state_length = 3
  )

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.