[R] Error creating a map with packages sf and tidyverse.
Bob Green
bgreen @end|ng |rom dy@on@br|@net@org@@u
Mon Jun 13 12:21:38 CEST 2022
I was hoping for advice about this code that I have run several
times. When I recently ran the code, I received the error
below:"Error in FUN(X[[i]], ...) : object 'fac' not found"
In R Studio the code runs, but instead of non-red countries being
white, they are darker grey.
Is 'fill=fac', no longer valid, or is there some other issue?
Any advice is appreciated,
Regards
Bob
> library(tidyverse)
-- Attaching packages
-----------------------------------------------------------------------------
tidyverse 1.3.1 --
v ggplot2 3.3.5 v purrr 0.3.4
v tibble 3.1.3 v dplyr 1.0.7
v tidyr 1.1.4 v stringr 1.4.0
v readr 2.1.1 v forcats 0.5.1
-- Conflicts
--------------------------------------------------------------------------------
tidyverse_conflicts() --
x dplyr::filter() masks stats::filter()
x dplyr::lag() masks stats::lag()
Warning messages:
1: In (function (kind = NULL, normal.kind = NULL, sample.kind = NULL) :
non-uniform 'Rounding' sampler used
2: In (function (kind = NULL, normal.kind = NULL, sample.kind = NULL) :
non-uniform 'Rounding' sampler used
> library(sf)
Linking to GEOS 3.9.1, GDAL 3.2.1, PROJ 7.2.1; sf_use_s2() is TRUE
Warning message:
package 'sf' was built under R version 4.1.3
>
>
>
> world_sf = map_data("world") %>%
+ filter(region != "Antarctica") %>%
+ mutate(region=replace(region, subregion=="Alaska", "USA_Alaska")) %>%
+ st_as_sf(coords=c("long","lat"), crs=4326) %>%
+ group_by(region, group) %>% summarise(geometry=st_combine(geometry)) %>%
+ st_cast("POLYGON") %>% summarise(geometry=st_combine(geometry))
`summarise()` has grouped output by 'region'. You can override using
the `.groups` argument.
>
> labs = tibble(region = c("Argentina", "Australia",
"Barbados","Brazil", "England","Fiji", "France", "French Polynesia",
"Ghana", "Italy","Japan", "New Zealand", "Papua New Guinea", "Peru",
"Portugal", "Samoa", "Sao Tome and Principe", "Senegal", "Solomon
Islands", "South Africa", "Spain", "Trinidad", "Tobago", "Turkey",
"UK", "Uruguay", "USA"))
> ggplot()+geom_sf(aes(fill=fac))+coord_sf(expand=FALSE)
Error in FUN(X[[i]], ...) : object 'fac' not found
>
> labels_sf = st_point_on_surface(world_sf) %>% right_join(labs, by="region")
Warning messages:
1: In st_point_on_surface.sf(world_sf) :
st_point_on_surface assumes attributes are constant over geometries of x
2: In st_point_on_surface.sfc(st_geometry(x)) :
st_point_on_surface may not give correct results for longitude/latitude data
>
>
> world_sf %>% mutate(fac = region %in% labs$region) %>%
+ ggplot()+geom_sf(aes(fill=fac))+coord_sf( expand=FALSE)+
+ theme(axis.title = element_blank(), legend.position = "none")+
+ scale_fill_manual(values=c("FALSE"=NA, "TRUE"="red"))
>
More information about the R-help
mailing list