0

I am trying to create a new column on a merged dataframe for the per capita value of variable p in different states. Then I am trying to put them onto a ggspatial map. Below is my code.

data(us_states)

#Merge
st_geometry(state_p) <- NULL  #bc R can't merge points and polygon
p_states <- merge(us_states, state_p, by.x = "NAME", by.y = "Name", all=T)

view(p_states)
# This all works fine

p_states %>% 
  summarize(p_capita = (state_n/total_pop_15)) %>% 
  print(p_states$p_capita)
#This prints in the console but not in a dataframe, more like in [this way which confuses me][1]

view(p_states)
#p_capita won't show up here



plot(st_geometry(us_states))
plot(p_states["p_capita"])
#this plot will not run
#the error message is "Error in `[.data.frame`(x, i) : undefined columns selected" 


  [1]: https://i.stack.imgur.com/wIM9B.png

I suspect it has something to do with the fact it's spatial data? This is my first time working with ggspatial so I'm out of my element.

Sed
  • 1
  • You just print it, where you want to assign it, try `p_states <- p_states %>% summarize(p_capita = (state_n/total_pop_15))`. – jay.sf Oct 02 '22 at 14:54
  • Unfortunately, when I do that it only shows p_capita and the 'geometry' which creates a solid color map when I plot it. [photo] (https://i.stack.imgur.com/NayvS.png) – Sed Oct 02 '22 at 15:15
  • Have you tried to use `.` when refering to something insde the pipe operator? i.e: p_states %>% summarize(p_capita = (state_n/total_pop_15)) %>% print(.$p_capita) – Sebek Oct 02 '22 at 15:23
  • @sebek Unfortunately it still shows just the p_capita and geometry, no states – Sed Oct 02 '22 at 16:10
  • when you just use `summarize` you are reducing the geometry. You are not specifying anything to group the data by other than geometry, which is why the states get dropped. add `p_states %>% group_by(state) %>% summarize(p_capita = (state_n/total_pop_15))`. You might need to change state to the actual variable name with the states name. – AndS. Oct 02 '22 at 19:43
  • Also, I disagree that you cant join points to polygons. You are really just trying to join the attribute tables to calculate some other variable for your map. – AndS. Oct 02 '22 at 19:45
  • @AndS. Thank you! That worked. It still won't map though...? Same error: "Error in `[.data.frame`(x, i) : undefined columns selected" Here's the full code `st_geometry(state_p) <- NULL #bc R can't merge points and polygon p_states <- merge(us_states, state_p, by.x = "NAME", by.y = "Name", all=T) p_states %>% group_by(NAME) %>% summarize(p_capita = (state_n/total_pop_15)) data(us_states) plot(st_geometry(us_states)) + plot(p_states["p_capita"], add = T)` – Sed Oct 03 '22 at 02:00
  • @AndS. Thank you! I was able to fix it! It was an error with the way I was plotting + your help with the group_by(), thanks! – Sed Oct 03 '22 at 02:14
  • No problem. I recommend looking into `geom_sf` from `ggplot2` for plotting `sf` objects. – AndS. Oct 03 '22 at 11:36

0 Answers0