我有一个巨大的 lapply 正在运行来下载数据文件。但看起来很笨拙。但 mapply 似乎不对,因为我不想要所有州/县的组合。我听说过关于 map() 的好消息。任何人都可以提供一个示例,说明如何在以下代码中使用 purrr() 命令“map”?
library(tidycensus)
library(sf)
mykey<-"youhavetogetyourownimafraid"
#variables to test out the function#############
x<-"06"
y<-"073"
z<-"2000"
setwd("N:/Dropbox/_BonesFirst/149_Transit_Metros_BG_StateSplit_by_R")
##################now the actual function#########################
get_Census <- function(x,y,z) {
name<-paste0("transitmetro_",x,"_",y,"_",z)
name
namefile<-get_decennial(geography = "block group",
variables = "P001001",
sumfile = "sf1",
key = mykey,
state = x, county = y,year = z,
geometry = TRUE)
st_write(namefile, paste0(name,".shp")) #tidycensus version of write OGR
}
#now, for all of them
CO<-c("013")
tibble04_10<-lapply(CO,get_Census,x="04",z="2000")
CO<-c("067","073","113")
tibble06_10<-lapply(CO,get_Census,x="06",z="2000")
CO<-c("005","031","035")
tibble08_10<-lapply(CO,get_Census,x="08",z="2000")
CO<-c("037","053","123")
tibble27_10<-lapply(CO,get_Census,x="27",z="2000")
CO<-c("119")
tibble37_10<-lapply(CO,get_Census,x="37",z="2000")
CO<-c("085","113","121","201")
tibble48_10<-lapply(CO,get_Census,x="48",z="2000")
CO<-c("035") #SLCO, utah
tibble49_10<-lapply(CO,get_Census,x="49",z="2000")
CO<-c("033","053") #King co, Seattle
tibble53_10<-lapply(CO,get_Census,x="53",z="2000")
EDIT
get_Census <- function(x,y,z) {
name<-paste0("transitmetro_",x,"_",y,"_",z)
name
namefile<-get_decennial(geography = "block group",
variables = "P001001",
sumfile = "sf1",
key = mykey,
state = x, county = y,year = z,
geometry = TRUE)
st_write(namefile, paste0(name,".shp")) #tidycensus version of write OGR
}
CO_list <- list(c("013"),
c("067","073","113"),
c("005","031","035"),
c("037","053","123"),
c("119"),
c("085","113","121","201"),
c("035"),
c("033","053"))
x_list <- c("04", "06", "08", "27", "37", "48", "49", "53")
z_list <- c("2000", "2000", "2000", "2000", "2000", "2000", "2000", "2000")
# BUILD LIST OF OBJECTS
tibble_list <- Map(function(CO, x, z) lapply(CO, function(i) get_Census(i, x, z)),
CO_list, x_list, z_list)
# NAME LIST OF OBJECTS: tibble04_10, tibble06_10, tibble08_10, ...
tibble_list <- setNames(tibble_list, paste0("tibble", x_list, "_10"))
print(tibble_list)
Yields:
从 2000 年十年一次的人口普查中获取数据
错误:结果 1 不是长度为 1 的原子向量
另外: 警告消息:
1:“004”不是佐治亚州各县的有效 FIPS 代码
2:“004”不是佐治亚州各县的有效 FIPS 代码
显示回溯
重新运行并调试
错误收集_(数据,key_col = compat_as_lazy(enquo(key)),value_col
= compat_as_lazy(enquo(value)), : 未使用的参数 (-NAME)