Maps包不适用于R markdown,但与R脚本完全兼容

问题描述 投票:0回答:1
---
date: "2/10/2020"
output: html_document
---
---------------------------------------
knitr::opts_chunk$set(echo = TRUE)

我正在使用“Harvard Database”中的选举文件。最初,我加载必要的程序包并进行一些数据清理,以仅获取有关在不同州赢得各州选举的候选人的数据。以下代码执行此操作。

list.of.packages <- c("maps", "dplyr", "tidyverse", "car", "RColorBrewer")
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
if(length(new.packages)) install.packages(new.packages)
data <- read.table("D:\\1976-2016-president.csv", header = TRUE, sep = ",")
library(maps)
library(dplyr)
library(tidyverse)
library(RColorBrewer)
y <- data %>% group_by(state,year) %>% arrange(desc(candidatevotes)) %>% slice(1) %>% ungroup()
y <- data.frame(y)
y <- y %>%
  mutate(color = case_when(
    party == "republican" ~ 1,
    party == "democrat" ~ 7,
    TRUE                      ~ 3
  ))

现在,我绘制2000年的选举结果。

temp <- y[y$year==2000,c("state", "state_fips","party","color")]
temp <- temp[match(paste(state.fips$fips),paste(temp$state_fips)),]
colpal <- RColorBrewer::brewer.pal(7, 'RdBu')
temp$quantcolors <- colpal[temp$color]
str(temp)
par(mfrow=c(1,1), mar=c(0,0,0,0))
map("state", col=temp$quantcolors, fill=TRUE)
title("Presidential election results by State in 2000")

但是,它引发了错误:

Error in as_mapper(.f, ...) : argument ".f" is missing, with no default
Calls: <Anonymous> ... withCallingHandlers -> withVisible -> eval -> eval -> map -> as_mapper

与R脚本完美配合。有人可以帮我弄清楚这里发生了什么吗?

r maps r-markdown knitr
1个回答
0
投票

当显式调用地图库时,代码工作得很好:

temp <- y[y$year==2000,c("state", "state_fips","party","color")]
temp <- temp[match(paste(state.fips$fips),paste(temp$state_fips)),]
colpal <- RColorBrewer::brewer.pal(7, 'RdBu')
temp$quantcolors <- colpal[temp$color]
str(temp)
par(mfrow=c(1,1), mar=c(0,0,0,0))
maps::map("state", col=temp$quantcolors, fill=TRUE)
title("Presidential election results by State in 2000")
© www.soinside.com 2019 - 2024. All rights reserved.