gpt4 book ai didi

通过输入 "ALL"返回函数中的所有值

转载 作者:行者123 更新时间:2023-12-04 10:01:36 26 4
gpt4 key购买 nike

我有一个函数,可以在输入州缩写(例如“KY”或“AL”)时列出所有州的邮政编码和每个邮政的人口。

我想在输入“ALL”时返回所有邮政编码和人口,但我似乎无法弄清楚如何做到这一点。我试图在函数中写一个 for 循环来实现这一点,但没有成功。

这是函数:

StatePop1 <- function(StAbb="KY"){
library(rjson)

St <- c('AL','AK','AZ','AR','CA','CO','CT','DE','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY')
FI <- c('01','02','04','05','06','08','09','10','12','13','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','37','38','39','40','41','42','44','45','46','47','48','49','50','51','53','54','55','56')
FIPS.table <- data.frame(St,FI,stringsAsFactors = FALSE)
StAbb <- toupper(StAbb)
fips_code <- FIPS.table[FIPS.table$St == StAbb,"FI"]
json_file <- paste("http://api.census.gov/data/2010/sf1?get=P0010001&for=zip+code+tabulation+area:*&in=state:",fips_code,sep="")
json_data <- fromJSON(file=json_file)
Pop <- as.data.frame(do.call("rbind", json_data), stringsAsFactors = FALSE)
names(Pop) <- c("Population","FIPS","ZipCode")
Pop <- Pop[-1,]
Pop$Population <- as.numeric(Pop$Population)
Pop$ZipCode <- as.character(Pop$ZipCode)
Pop$State <- StAbb
Pop <- Pop[,c("State","ZipCode","Population")]

return(Pop)
}

任何帮助,将不胜感激。

最佳答案

您只需要矢量化输入,因此它可以采用任意数量的状态,如果它是“全部”,则将其设为整个状态列表(也内置为 state.abb )。我切换到 jsonlite因为它更快,但应该是相同的功能。

StatePop1 <- function(StAbb="KY"){
library(jsonlite)
if (length(StAbb) == 1 && StAbb == "ALL") StAbb <- state.abb # check for ALL
FI <- c('01','02','04','05','06','08','09','10','12','13','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','37','38','39','40','41','42','44','45','46','47','48','49','50','51','53','54','55','56')
FIPS.table <- data.frame(St=state.abb, FI, stringsAsFactors = FALSE)
StAbb <- toupper(StAbb)
fips_code <- FIPS.table[FIPS.table$St %in% StAbb,"FI"] # change to %in%
json_file <- paste("http://api.census.gov/data/2010/sf1?get=P0010001&for=zip+code+tabulation+area:*&in=state:",fips_code,sep="")
json_data <- lapply(json_file, jsonlite::fromJSON)
Pop <- data.frame(do.call(rbind, json_data), stringsAsFactors = FALSE) # dont need as.data.frame
names(Pop) <- c("Population","FIPS","ZipCode")
Pop <- Pop[-1,]
Pop$Population <- as.numeric(Pop$Population)
Pop$ZipCode <- as.character(Pop$ZipCode)
Pop$State <- FIPS.table[match(Pop$FIPS, FIPS.table$FI), "St"] # match states
Pop <- Pop[,c("State","ZipCode","Population")]
return(Pop)
}

## Example, now passing any of the following should work
res <- StatePop1('KY')
res <- StatePop1(c('NH','KY'))
res <- StatePop1('All')

关于通过输入 "ALL"返回函数中的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33705023/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com