I'd like to create a map that shows the value of variable for a given state. The dataset contains around a thousand variables and is at the state level, for about 100 years.
The code I have and works is:
plot_usmap(data = database, values = "var1") + scale_fill_continuous(
low = "white", high = "blue", na.value="light gray", name = "Title of graph", label = scales::comma
) + theme(legend.position = "right")
Now what I'd like to do is create this map for a list of about 15 variables and 10 years. I'm usually a STATA user, and there I could define a variable list and then loop through the variable list. On page 7 of this document of "A Quick Introduction to R (for Stata Users)", I tried applying the following solution:
vars <- c("database$var1", "database$var2", "database$var3","database$var4", "database$var5", "database$var6", "database$var7", "database$var8", "database$var9", "database$var10", "database$var11", "database$var12")
for(var in vars) {
v <- get(var)
plot_usmap(data = darabase, values = "v") +
scale_fill_continuous(low = "white", high = "blue", na.value="light gray", name = "v", label = scales::comma) + theme(legend.position = "right")}
With this code, I get error "Error in get(var) : object 'database$var1' not found. When I try view(database$var1) it appears. The next problem is that I'd like the name of the graph to be the label of the variable rather than the variable. In the example above, I'd restricted the whole data to only include 1 year, so if there's a solution to set the code up that I could use the whole database but map only select years, that would be great.
Any insights would be appreciated! I read that in R, "for" isn't used as much, so if there is a better way to do it, please let me know.