看起来好像文件已正确下载,但您是对的:如果您使用read.csv 将数据加载到R 中,那么某些列会被解释为numeric,因此它们会丢失前导零。
获取下载文件的代码 -
stateFIPScodes<-seq(10,13,1)
for(i in seq_along(stateFIPScodes)){
code <- stateFIPScodes[[i]]
URL <- paste0("https://www.census.gov/popest/data/intercensal/county/files/CO-EST00INT-ALLDATA-", code, ".csv")
destfile <- paste0("state2000_2010_",code,".csv")
download.file(URL, destfile)
}
如果我们使用基数 read.csv,我们不会得到尾随零:
library(dplyr)
read.csv("state2000_2010_10.csv") %>%
select(1:5) %>%
head
#> SUMLEV STATE COUNTY STNAME CTYNAME
#> 1 50 10 1 Delaware Kent County
#> 2 50 10 1 Delaware Kent County
#> 3 50 10 1 Delaware Kent County
#> 4 50 10 1 Delaware Kent County
#> 5 50 10 1 Delaware Kent County
#> 6 50 10 1 Delaware Kent County
这是因为前几列是作为数字读入的。
read.csv("state2000_2010_10.csv") %>% str()
#> 'data.frame': 780 obs. of 50 variables:
#> $ SUMLEV : int 50 50 50 50 50 50 50 50 50 50 ...
#> $ STATE : int 10 10 10 10 10 10 10 10 10 10 ...
#> $ COUNTY : int 1 1 1 1 1 1 1 1 1 1 ...
有两种方法可以解决这个问题:
- 手动将数据类型传递给
read.csv,或者通过添加colClasses = "character" 来阻止所有转换。
- 使用正确处理它的
readr::read_csv。
我们可以阻止自动强制:
read.csv("state2000_2010_10.csv", colClasses = "character") %>% str()
#> 'data.frame': 780 obs. of 50 variables:
#> $ SUMLEV : chr "050" "050" "050" "050" ...
#> $ STATE : chr "10" "10" "10" "10" ...
#> $ COUNTY : chr "001" "001" "001" "001" ...
#> $ STNAME : chr "Delaware" "Delaware" "Delaware" "Delaware" ...
您需要选择要转换为 as.numeric 的列。
或者您可以选择列,例如
read.csv("state2000_2010_10.csv",
colClasses = c(
SUMLEV = "character",
STATE = "numeric",
COUNTY = "character"
)) %>%
select(1:5) %>%
head
#> SUMLEV STATE COUNTY STNAME CTYNAME
#> 1 050 10 001 Delaware Kent County
#> 2 050 10 001 Delaware Kent County
#> 3 050 10 001 Delaware Kent County
#> 4 050 10 001 Delaware Kent County
#> 5 050 10 001 Delaware Kent County
#> 6 050 10 001 Delaware Kent County
其次,您可以使用readr,它具有更智能的列类型推断:
#> read_csv("state2000_2010_10.csv") %>%
#> select(1:5) %>%
#> head
#> # A tibble: 6 × 5
#> SUMLEV STATE COUNTY STNAME CTYNAME
#> <chr> <int> <chr> <chr> <chr>
#> 1 050 10 001 Delaware Kent County
#> 2 050 10 001 Delaware Kent County
#> 3 050 10 001 Delaware Kent County
#> 4 050 10 001 Delaware Kent County
#> 5 050 10 001 Delaware Kent County
#> 6 050 10 001 Delaware Kent County